In JavaScript, the Execution Context (EC) is an environment where JavaScript code is executed. It determines the scope, available variables, functions, and the value of this.

Types of Execution Contexts

JavaScript has three types of execution contexts:

  1. Global Execution Context (GEC)
    • Created when the JavaScript file starts executing.
    • Contains the global object (window in browsers, global in Node.js).
    • this refers to the global object.
  2. Function Execution Context (FEC)
    • Created whenever a function is invoked.
    • Has its own variables, function definitions, and this binding.
    • Each function call gets its own execution context.
  3. Eval Execution Context
    • Created when eval() is used.
    • Executes JavaScript code inside a string (not recommended for security reasons).

Execution Context Lifecycle

Each execution context goes through three phases:

  1. Creation Phase (Memory Allocation)
    • Creates the Global Object (e.g., window in browsers).
    • Sets up the “this” binding.
    • Stores function declarations in memory.
    • Allocates memory for variables (var is hoisted with undefined, let & const are in TDZ).
  2. Execution Phase
    • Executes the code line by line.
    • Assigns values to variables.
    • Executes function calls.
  3. Destruction Phase
    • The execution context is removed from the call stack once execution is complete.

Similar Posts