JavaScript Execution Context

JavaScript execution context defines how and where code is evaluated and executed. Every time JavaScript runs a script, a function, or a block, it creates an execution context to manage variables, scope, and this binding.


Types of Execution Context

JavaScript has three main execution contexts:

1. Global Execution Context (GEC)

  • Created when the JavaScript file is loaded
  • Only one global context exists per program
  • Creates:
    • Global object (window in browsers, global in Node.js)
    • this keyword
    • Global variables and functions

Example:

var x = 10;
function test() {
  console.log(x);
}

Here, x and test() belong to the global execution context.


2. Function Execution Context (FEC)

  • Created every time a function is invoked
  • Each function call gets its own execution context
  • Contains:
    • Arguments object
    • Local variables
    • Function scope
    • this value

Example:

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

Calling add() creates a new function execution context.


3. Eval Execution Context (Rare)

  • Created when eval() executes code
  • Avoided in production due to security and performance issues

Phases of Execution Context

Each execution context is created in two phases:

1. Memory Creation Phase (Hoisting Phase)

  • Variables are allocated memory and set to undefined
  • Functions are stored entirely in memory
  • this is initialized

Example:

console.log(a); // undefined
sayHi(); // works

var a = 5;
function sayHi() {
  console.log("Hi");
}

2. Execution Phase

  • Code is executed line by line
  • Variables get assigned actual values
  • Functions are executed when invoked

Execution Context Stack (Call Stack)

JavaScript uses a stack structure to manage execution contexts.

How it works:

  1. Global Execution Context is pushed first
  2. Function call creates a new context and pushes it
  3. Function completes → context is popped
  4. Control returns to the previous context

Example:

function one() {
  two();
}
function two() {
  console.log("Hello");
}
one();

Call stack order:

  • Global → one() → two()

Relation with Scope and Closures

Execution context defines:

  • Variable environment
  • Lexical scope

Closures work because inner functions retain access to the lexical environment of their execution context even after the outer function finishes execution.


Common Interview Points

  • Execution context is created before code execution
  • Functions are fully hoisted, variables are partially hoisted
  • Call stack controls execution order
  • Each function call creates a new execution context

Summary

  • Execution context manages code execution
  • Three types: Global, Function, Eval
  • Two phases: Memory creation and Execution
  • Call stack tracks execution contexts

Understanding execution context is critical for debugging, closures, hoisting, and asynchronous JavaScript behavior.

Share via
Copy link