JavaScript is a single-threaded programming language, meaning it executes code one operation at a time. Understanding how JavaScript works under the hood can help you write more efficient code, debug issues faster, and avoid common pitfalls like callback hell and performance bottlenecks.
In this guide, we’ll break down two fundamental concepts:
Execution Context – How JavaScript manages code execution.
Call Stack – How JavaScript keeps track of function calls
1. Execution Context
Think of Execution Context as a box where JavaScript runs your code. Every time JavaScript executes something, it creates this box to store variables, functions, and the environment in which the code runs.
Phases of the JavaScript Execution Context
There are two phases of JavaScript execution context:
Creation phase: In this phase, the JavaScript engine creates the execution context and sets up the script's environment. It determines the values of variables and functions and sets up the scope chain for the execution context.
Execution phase: In this phase, the JavaScript engine executes the code in the execution context. It processes any statements or expressions in the script and evaluates any function calls.
Example: Execution Context in Action
What Happens Behind the Scenes?
Global Execution Context (GEC) is created.
var name
is stored in memory and set toundefined
, then later assigned"Alice"
.The function
greet()
is stored in memory.
When
greet()
is called, a new Function Execution Context (FEC) is created.var message
is stored and assigned"Hello, Alice"
.console.log(message)
runs and prints"Hello, Alice"
.
After
greet()
finishes, its execution context is removed from memory.
2. The Call Stack
JavaScript uses the Call Stack to manage function execution. The Call Stack is a LIFO (Last In, First Out) data structure, meaning the last function added is the first one removed.
How the Call Stack Works
When a function is called, JavaScript pushes it onto the stack.
When the function completes, it is popped off the stack.
If a function calls another function, the new function is pushed onto the stack, and JavaScript waits for it to finish before continuing
Call Stack Execution
first()
is pushed onto the stack.Inside
first()
,second()
is called →second()
is pushed onto the stack.Inside
second()
,third()
is called →third()
is pushed onto the stack.third()
executes and is popped off the stack.second()
finishes and is popped off the stack.first()
finishes and is popped off the stack.
Final output
First function
Second function
Third function
Failed to render LaTeX expression — no expression found
Failed to render LaTeX expression — no expression found
Wow, very simple and easy to understand behind the scenes view. I love it.