Execution Context
Overview
The Execution Context is the environment where JavaScript code is evaluated and executed.
Think of it as a restaurant kitchen. The 'Global Execution Context' is the main kitchen where global variables (ingredients) are stored. Every time a function is called, a new 'Function Execution Context' (a new chef's station) is created to handle that specific recipe, complete with its own local variables.
Syntax
1. Memory Creation Phase: JS scans the code and allocates memory for variables (sets x to undefined) and functions.
2. Code Execution Phase: JS runs the code line by line, assigning 10 to x when it reaches line 2.
console.log(x); // undefined (not an error!)
var x = 10;
console.log(x); // 10Common Pitfalls
- Not understanding the two phases, which leads to confusion about why variables behave weirdly (like returning
undefinedinstead of throwing an error) when accessed before declaration.
Interview Questions
It is the default context created when a JS file runs. It creates a global object (like window in the browser) and a this keyword pointing to that global object.
Real-World Example
When debugging complex apps, you can literally see Execution Contexts piling up in the browser's 'Call Stack' panel. Each context represents a function currently running.
function prepareDough() {
// 3. New Context created for prepareDough
}
function bakePizza() {
// 2. New Context created for bakePizza
prepareDough();
}
// 1. Global Context starts
bakePizza();Check Your Knowledge
Test your understanding of Execution Context with these quick questions.