Home Courses Execution Context Explained

Execution Context Explained

What is Execution Context?

Execution Context is the environment in which JavaScript code is executed.

In simple terms:

It is the place where your code runs and decides how variables and functions behave.


Why Execution Context is Important

Execution context controls:

  1. Which variables are accessible (scope)
  2. When functions are executed
  3. Order of execution
  4. How hoisting works internally


Types of Execution Context

There are two main types:

1. Global Execution Context (GEC)

  1. Created when the JavaScript program starts
  2. Only one global execution context exists
  3. All global variables and functions are stored here

Example:


let a = 10;

function test() {
console.log("Hello");
}

test();

Here:

  1. a → stored in global memory
  2. test() → stored in global memory

2. Function Execution Context (FEC)

  1. Created every time a function is called
  2. Each function call creates a new execution context
  3. Destroyed after function execution completes

Key Point:

Multiple function execution contexts can exist, but only one global execution context exists.


Phases of Execution Context

Each execution context has two phases:


Memory Creation Phase

Also called Creation Phase

In this phase:

  1. Memory is allocated for variables
  2. Variables are initialized with undefined
  3. Functions are stored entirely in memory

Example:


var a = 10;

function greet() {
console.log("Hi");
}

During memory phase:


a = undefined
greet = function() {...}

2. Code Execution Phase

In this phase:

  1. Code runs line by line
  2. Variables get actual values
  3. Functions are executed when called

After execution:


a = 10


Execution Flow (Step-by-Step)

  1. Global Execution Context is created
  2. Memory Creation Phase runs
  3. Code Execution Phase runs
  4. When a function is called:
  5. New Function Execution Context is created
  6. Function executes
  7. Function Execution Context is destroyed
  8. Control returns to Global Execution Context


Relationship Between Hoisting and Execution Context

Hoisting happens because of the Memory Creation Phase.

  1. Variables are stored with undefined
  2. Functions are stored completely
  3. That’s why you can use them before declaration

Example:


console.log(a); // undefined
var a = 10;

This works because:

  1. a is already created in memory before execution


Share this lesson: