Skip to content

Latest commit

 

History

History
96 lines (67 loc) · 2.69 KB

File metadata and controls

96 lines (67 loc) · 2.69 KB

How function works in JS & Variable Environment

How Functions Work in JavaScript

When you declare and call a function, JavaScript uses the Execution Context mechanism to run it.

Step 1: Function Declaration

A function can be created using:

Function Declaration (Statement)

function greet() {
  console.log('Hello');
}

Function Expression

const greet = function () {
  console.log('Hello');
};

Step 2: When a Function is Called

Every time a function is invoked:

  1. A Function Execution Context (FEC) is created.
  2. This FEC is pushed onto the call stack.
  3. Inside this context, two main components are created:
    • Variable Environment
    • Scope Chain & Outer Environment Reference

Variable Environment

The Variable Environment is part of the execution context and holds:

  • Variables declared inside the function (var, let, const)
  • Function declarations inside the function
  • Arguments object (in non-arrow functions)

It's basically the "local memory" for that function execution.

Example:

function add(a, b) {
  var sum = a + b;
  function double(x) {
    return x * 2;
  }
  return double(sum);
}

console.log(add(2, 3)); // 10

Behind the Scenes:

When add(2, 3) is called:

  1. A Function Execution Context is created.
  2. Variable Environment for add looks like:
{
  arguments: { 0: 2, 1: 3, length: 2 },
  a: 2,
  b: 3,
  sum: undefined,   // created during creation phase, value assigned in execution phase
  double: function(x) { return x * 2; }
}
  1. After sum = a + b → sum becomes 5.
  2. double(sum) is called → creates a new FEC for double.

Functions & Scope Chain

  • Functions remember the scope in which they were created.
  • This allows for closure behavior (accessing variables from the parent scope).
  • Even after the parent function finishes, inner functions can still access variables from the outer environment.

Key Interview Points

  • Each function call gets its own execution context — no sharing of local variables between calls.
  • Variable Environment stores local variables and arguments.
  • The scope chain lets functions access outer variables.
  • Closures happen when a function retains access to the variable environment of its parent after the parent has returned.

Interview Soundbite:

"When a function is invoked, JavaScript creates a Function Execution Context with its own Variable Environment, which stores the function's local variables, arguments, and inner function declarations. This environment is linked to its outer scope through the scope chain, enabling access to variables outside the function. Each function call has its own isolated variable environment."