The Execution Context is the environment in which JavaScript code runs. It determines how code is interpreted and what data (variables, functions) it has access to at any point.
Two Phases of Execution Context
Phase 1: Memory Creation Phase- All variables and function declarations are stored in memory.
- Variables are initialized with the value
undefined
. - Function declarations are hoisted with their full definitions.
- The code is executed line by line.
- Variables are assigned their actual values.
- Functions are invoked, and each creates its own execution context.
Types of Execution Context
- Global Execution Context (GEC): Automatically created when a script runs. It handles global code.
- Function Execution Context (FEC): Created each time a function is called. Each has its own local variables and scope.
- Eval Execution Context: Created only
when using
eval()
. Rarely used and discouraged.
Example Code
Use browser developer tools (F12) to step through the execution using the debugger.
debugger;
fun1();
var userName = "Hey";
var age = 20;
function fun1() {
const a = 20;
const b = 30;
const result = fun2(a, b);
console.log("Result from fun2:", result);
}
function fun2(a, b) {
return a + b;
}