Deep Dive Into JavaScript Execution Contexts: How Your Code Actually Runs

Understand how JavaScript handles code execution through execution contexts, and learn how it impacts variable scope and function execution.

🧠 What is an Execution Context?

  • JavaScript is a single-threaded and synchronous programming language.
  • This means it can only execute one piece of code at a time.
  • To handle execution in an organized way, JavaScript uses something called an Execution Context.

Every time a JavaScript program runs, an execution context is created.


Phases of JavaScript Execution Context

There are two phases in the lifecycle of an execution context:

1. Creation Phase (a.k.a. Memory Allocation Phase)

During this phase:

  • Variables declared with var are initialized with undefined.
  • Functions are stored in memory with their full definitions.
  • No actual code execution happens at this stage.

Example:

var a = 10; 
var b = 20; 
const add = (a, b) => {
  const sum = a + b;
  return sum;
}
👇 Here’s what happens in the Creation Phase:
  • var a = undefined
  • var b = undefined
  • const add = function definition (Note: for const, it's not hoisted like var, but the memory space is reserved)
  • The body of the function (const sum and return sum) isn’t executed yet.

This entire step is purely about setting up memory space for variables and functions.


2. Execution Phase

In this phase:

  • Code is executed line by line.
  • Variables get assigned their actual values.
  • Functions are invoked and executed.

Continuing the above example, the Execution Phase would look like:

  • a = 10
  • b = 20
  • add is invoked → sum = a + b = 30
  • return 30

Types of Execution Contexts in JavaScript

JavaScript uses two main types of execution contexts:


1. Global Execution Context (GEC)

  • This is the default execution context.
  • It’s created when the JavaScript engine starts executing your code.
  • All variables and functions that are not inside any function exist in the global context.
  • The value of this inside the GEC refers to the global object (e.g., window in browsers).

2. Function Execution Context (FEC)

  • A new execution context is created each time a function is called.
  • It includes its own creation and execution phases.
  • Variables defined within the function exist only in this local context.
  • this in this context refers to the object that invoked the function.

Key Takeaways

  • JavaScript executes code in phases — first memory allocation, then actual execution.
  • There are two types of execution contexts — Global and Function.
  • Each function call creates a new isolated environment with its own scope.
  • Understanding this helps in debugging hoisting, scope issues, and this keyword confusion.