01 How JavaScript works & Execution context ?

π₯ 01. How JavaScript Works β Overview
JavaScript is:
Single-threaded β one task at a time
Synchronous by default (but supports async with Web APIs)
Interpreted/Just-in-time compiled (V8 engine etc.)
JavaScript runs inside the JavaScript Engine (e.g., V8 in Chrome, SpiderMonkey in Firefox). It consists of:
Call Stack
Memory Heap
Execution Context
Event Loop
βοΈ JavaScript Engine Workflow
Parsing Phase (Compile Time)
Code is parsed into tokens
Converted into Abstract Syntax Tree (AST)
Variables and function declarations are hoisted
Execution Phase
JS runs top-to-bottom
Creates Execution Contexts for each scope
Handles function calls using the Call Stack
π§ Execution Context (EC) β Core Concept
An Execution Context is an environment where JavaScript code is evaluated and executed.
There are 3 main types:
Global Execution Context (GEC)
Function Execution Context (FEC)
Eval Execution Context (rarely used)β
πΉ Global Execution Context
Created when the JS file is loaded:
Creates a global object (
window
in browsers,global
in Node.js)Binds
this
to global objectHoists global variables and functions
Example:
var a = 10;
function greet() {
console.log("Hello");
}
β GEC is created, where:
a
is added to memorygreet
function is hoisted
πΉ Function Execution Context
Created every time a function is invoked:
Has its own Variable Environment (VE)
Arguments, local variables, inner functions live here
Forms part of the Call Stack
Example:
function add(x, y) {
var total = x + y;
return total;
}
add(3, 4);
When add(3, 4)
is called:
New FEC is created
Parameters
x=3
,y=4
, localtotal=7
FEC is popped off after return
π¦ Whatβs Inside an Execution Context?
Every EC contains:
Variable Environment (VE)
var
,function
declarationsarguments
object
Lexical Environment
Tracks where variables/functions were defined
Helps with scope chain
this
Binding- Depends on how a function is called
π Execution Stack (Call Stack)
The Call Stack manages Execution Contexts in a LIFO manner:
function one() {
two();
}
function two() {
console.log("2");
}
one();
Call Stack Flow:
Global EC
β one() EC
β two() EC
β console.log() EC
Each function creates a new EC which is pushed onto the stack, then popped off when done.
π§ Summary
Term | Meaning |
Execution Context | The environment where code is run |
Global EC | Created once when script loads |
Function EC | Created every time a function runs |
Call Stack | Tracks active function calls |
Variable Environment | Stores function variables & arguments |
π Visual Mind Map
JavaScript Engine
ββ Memory Heap
ββ Call Stack
β ββ GEC
β ββ FEC
β ββ Eval EC (rare)
ββ Event Loop (later topic)
Subscribe to my newsletter
Read articles from Kamlesh Choudhary directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
