what is GEC
What is GEC?
The Global Execution Context is the first execution context created when a JavaScript program starts.
It consists of two main phases:
Creation Phase (Memory Creation Phase)
JavaScript sets up memory for variables and functions.
Variables (
var) are hoisted and set toundefined.Functions are hoisted with their entire definition.
Execution Phase
Code is executed line by line.
Variables are assigned their actual values.
Example:
var a = 10;
function greet() {
console.log("Hello, World!");
}
greet();
console.log(a);
Step 1: Creation Phase
Before execution starts, JavaScript scans the code and allocates memory.
a→ created in memory, initial value =undefinedgreet→ entire function stored in memory
So, memory looks like:
a: undefined
greet: ƒ greet() { console.log("Hello, World!"); }
Step 2: Execution Phase
Now the code runs line by line.
var a = 10;
→ais assigned10.greet();
→ Function is invoked, creates Function Execution Context (FEC) forgreet.
→ Inside it,console.log("Hello, World!");prints:Hello, World!console.log(a);
→ Prints:10Example with Nested Functions
var a = 10; function first() { var b = 20; second(); console.log("Inside first, b =", b); } function second() { var c = 30; console.log("Inside second, c =", c); } first(); console.log("In global, a =", a);
Step-by-Step Execution (with GEC and FEC)
1. Creation Phase (Global Execution Context - GEC)
Memory allocation before any code runs:
a: undefined first: ƒ first() { ... } second: ƒ second() { ... }
2. Execution Phase
Line
var a = 10;→ assigns10toa.Next,
first();→ a new Function Execution Context (FEC) is created forfirst().
3. Inside first()
Creation phase for first():
b: undefined
Execution:
b = 20;second();→ another FEC is created forsecond(), pushed on top of the Call Stack.
4. Inside second()
Creation phase for second():
c: undefined
Execution:
c = 30;console.log("Inside second, c =", c);Inside second, c = 30
After execution, second() FEC is removed (popped from Call Stack).
5. Back to first()
Next line:
console.log("Inside first, b =", b);Inside first, b = 20
first() FEC is now destroyed.
6. Back to Global Context
Last line:
console.log("In global, a =", a);In global, a = 10
GEC is removed after full execution ends.
Call Stack Representation
Start: [ GEC ]
first() called → [ GEC → first() FEC ]
second() called → [ GEC → first() FEC → second() FEC ]
second() ends → [ GEC → first() FEC ]
first() ends → [ GEC ]
End: [ ]