Have you ever wondered how JavaScript actually runs your code behind the scenes? Every time you run a JavaScript program, a special environment is created automatically by the JavaScript engine. This environment is called the Execution Context.
Understanding execution context is very important because it explains how variables, functions, and code execution actually work internally.
JavaScript Execution Context – Memory and Execution Flow
1. What is Execution Context?
Execution Context is the environment where JavaScript code is executed. Whenever a program runs, JavaScript creates this environment automatically.
You can think of it as a box where all variables, functions, and execution steps are managed.
2. Two Main Parts of Execution Context
Every execution context has two important sections:
- Memory Section (Variable Environment)
- Execution Section (Thread of Execution)
Memory Section
In this phase, JavaScript prepares memory before executing code.
b → undefined
add → function stored
Explanation:
- Variables are stored with value
undefined - Functions are stored completely in memory
- No code is executed yet
Execution Section
In this phase, JavaScript executes code line by line.
Values are assigned and functions are called.
3. Example Program
var a = 5;
var b = 10;
function add(){
console.log(a + b);
}
add();
4. Step-by-Step Execution
Step 1: Memory Creation Phase
b → undefined
add → function stored
Step 2: Execution Phase
b = 10
add() → 15
Final Output:
5. How JavaScript Executes Code
JavaScript follows a single-threaded execution model.
- Only one operation runs at a time
- No parallel execution
- Execution happens sequentially
6. Important Concept: Call Stack
JavaScript uses something called a Call Stack to manage execution.
- Functions are pushed into the stack when called
- Removed when execution is completed
- Follows LIFO (Last In First Out)
7. Asynchronous Behavior
Even though JavaScript is single-threaded, it can handle asynchronous operations using:
- Callbacks
- Promises
- Async/Await
Execution Context = environment where code runs
Memory Phase → variables initialized as undefined
Execution Phase → code runs line by line
Conclusion
Understanding execution context gives you deep insight into how JavaScript works internally. This is the foundation for advanced topics like hoisting, closures, and asynchronous programming.
You now understand JavaScript execution like a pro 🚀