02 How JavaScript code is Executed & Call Stack

π JavaScript Code Execution Process
JavaScript is a single-threaded, synchronous, non-blocking language that uses an event-driven model with a call stack, heap, Web APIs, task queue, and event loop.
π Step-by-Step: How JS Executes Code
Parsing & Compilation Phase
Code is parsed by the JS engine (e.g., V8 in Chrome).
Function and variable declarations are hoisted.
Scope and memory are set up.
Execution Phase
Code runs top to bottom, line by line.
Functions are pushed/popped from the call stack when invoked.
Variables are resolved using the scope chain.
π Components of JavaScript Runtime
1. Call Stack
A LIFO (Last In, First Out) structure that tracks function calls.
function a() {
b();
}
function b() {
console.log("Hello");
}
a();
π Call Stack Flow:
Global()
β a()
β b()
β console.log()
Stack Push/Pop:
Global()
β pushed firsta()
β pushedb()
β pushedconsole.log()
β pushed β poppedb()
β poppeda()
β poppedGlobal()
β popped
2. Memory Heap
Where all objects, arrays, and functions are stored.
Unstructured region for dynamic memory allocation.
3. Web APIs (Browser Environment)
JS has access to browser-provided APIs like:
setTimeout
DOM Events
Fetch/XHR
These run outside the JS engine.
4. Callback / Task Queue
After a Web API (like setTimeout
) finishes, it sends the callback to the task queue, waiting for the call stack to be empty.
5. Event Loop
Continuously checks if the call stack is empty.
If it is, it moves the first task from the queue to the stack.
β±οΈ Example with setTimeout
console.log("1");
setTimeout(() => {
console.log("2");
}, 0);
console.log("3");
Output:
1
3
2
π What Happens:
console.log("1")
β Call Stack β logs 1setTimeout
β Web API β after 0ms β pushes callback to queueconsole.log("3")
β Call Stack β logs 3Call Stack is now empty β Event Loop moves callback β Call Stack β logs 2
π§ Key Concepts
Concept | Description |
Call Stack | Tracks function calls |
Memory Heap | Stores variables and objects |
Web APIs | Browser features (timers, DOM, etc.) |
Callback Queue | Stores async tasks waiting to run |
Event Loop | Moves tasks from queue to stack when ready |
π― Visual Summary
βββββββββββββββ ββββββββββββββ
β Call Stack β β Task Queue β
ββββββ²ββββ¬βββββ ββββββ¬ββββ²βββββ
β β β β
β ββ console.log() β ββ (After async complete)
β β
β βββββββββββββββ β
ββββΆβ Web APIs ββββββ
βββββββββββββββ
Subscribe to my newsletter
Read articles from Kamlesh Choudhary directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
