Call Stack and Execution Context



This content originally appeared on DEV Community and was authored by AmanGupta1703

What is a Callstack?

  • It is part of the JavaScript engine.
  • A part of the JavaScript engine that keeps track of function calls.
  • It is a data structure that operates on a LIFO (Last-In-First-Out) basis to remove an execution context from the Call Stack.
  • – The first item pushed to the stack is the Global Execution Context. Each time a function is invoked, a new Function Execution Context is added (pushed) on top.
  • Once a function completes, its context is popped off the stack.

What is an Execution Context?

  • It is the environment in which JavaScript code is evaluated and executed.
  • It goes through two main phases:

    1. Creation Phase
    2. Execution Phase
  • The engine scans the code and allocates memory for variables and functions.

  • Functions are hoisted with their full definitions.

  • Variables declared with var are hoisted and initialised with undefined.

  • Variables declared with let and const are hoisted but remain uninitialized — they are in the Temporal Dead Zone (TDZ).

  • Primitive values are stored in the Call Stack; reference values (like objects) are stored in the Heap.

2. Execution Phase

  • The code is executed line by line.
  • Variables declared with var, let, and const are assigned their actual values.
  • Accessing a let or const variable before its declaration results in a ReferenceError due to the TDZ.

Temporal Dead Zone (TDZ)

  • The TDZ for a let or const variable starts at the beginning of its scope and ends when the variable is declared.
  • Accessing the variable in this zone will throw a ReferenceError.


This content originally appeared on DEV Community and was authored by AmanGupta1703