Most beginners learn JavaScript by writing variables, functions, loops, and events. However, professional developers also understand what happens behind the scenes when JavaScript code executes.
Consider the following code:
console.log("Start");
setTimeout(
function()
{
console.log("Timer");
},
0
);
console.log("End");
Many beginners expect the output to be:
Start
Timer
End
But the actual output is:
Start
End
Timer
Why does this happen?
To answer this question, we must understand:
JavaScript Runtime
Call Stack
Web APIs
Callback Queue
Event Loop
These concepts form the foundation of modern JavaScript and are frequently asked in interviews.
Why Understanding JavaScript Internals is Important
Understanding JavaScript internals helps developers:
Write better code
Debug applications
Improve performance
Understand asynchronous programming
Master Promises and Async/Await
Without understanding these concepts, asynchronous JavaScript often feels confusing.
JavaScript is Single-Threaded
JavaScript executes code using a single thread.
This means:
One Task
at a Time
JavaScript can execute only one statement at a given moment.
Example:
console.log("A");
console.log("B");
console.log("C");
Output:
A
B
C
Execution occurs sequentially.
What is JavaScript Runtime?
The JavaScript Runtime is the environment where JavaScript executes.
In browsers, it consists of:
JavaScript Engine
Call Stack
Web APIs
Callback Queue
Event Loop
JavaScript Runtime Architecture
Browser
┌───────────────────────┐
│ JavaScript Engine │
└──────────┬────────────┘
│
┌─────▼─────┐
│ Call Stack│
└─────┬─────┘
│
┌──────────▼───────────┐
│ Web APIs │
└──────────┬───────────┘
│
┌─────▼─────┐
│ Callback │
│ Queue │
└─────┬─────┘
│
┌─────▼─────┐
│Event Loop │
└───────────┘
What is the JavaScript Engine?
The JavaScript Engine executes JavaScript code.
Popular engines:
| Browser | Engine |
|---|---|
| Chrome | V8 |
| Edge | V8 |
| Firefox | SpiderMonkey |
| Safari | JavaScriptCore |
The engine reads and executes JavaScript instructions.
What is the Call Stack?
The Call Stack is a data structure that keeps track of function execution.
Whenever a function is called:
Function Added
to Stack
When execution finishes:
Function Removed
from Stack
The stack follows:
LIFO
Last In First Out
Call Stack Example
function one()
{
two();
}
function two()
{
three();
}
function three()
{
console.log("Hello");
}
one();
Output:
Hello
Step-by-Step Dry Run
Initial Stack:
Empty
When one() executes:
one()
Inside one():
two()
one()
Inside two():
three()
two()
one()
Inside three():
console.log()
three()
two()
one()
After execution:
Empty
Everything is removed from the stack.
Visual Representation
┌────────────┐
│console.log │
├────────────┤
│ three() │
├────────────┤
│ two() │
├────────────┤
│ one() │
└────────────┘
Stack Push Operation
Adding a function:
Push
Example:
one();
Adds:
one()
to the stack.
Stack Pop Operation
Removing a function:
Pop
After function completion:
one()
is removed.
What is Stack Overflow?
When functions keep calling themselves endlessly, the stack becomes full.
Example:
function test()
{
test();
}
test();
Output:
Maximum Call Stack Size Exceeded
Why Stack Overflow Happens
Execution:
test()
↓
test()
↓
test()
↓
test()
↓
Forever...
Stack memory becomes exhausted.
What are Web APIs?
JavaScript itself does not provide features like:
Timers
DOM Manipulation
HTTP Requests
Geolocation
These are provided by the browser.
They are called:
Web APIs
Examples of Web APIs
setTimeout()
setInterval()
fetch()
DOM Events
Geolocation
Local Storage
Example
setTimeout(
function()
{
console.log("Hello");
},
3000
);
The timer is handled by:
Web API
not by the Call Stack.
How setTimeout Works
Example:
console.log("Start");
setTimeout(
function()
{
console.log("Timer");
},
2000
);
console.log("End");
Execution Flow
Step 1:
console.log("Start")
Output:
Start
Step 2:
setTimeout
moves to:
Web API
Timer begins.
Step 3:
console.log("End")
Output:
End
After 2 Seconds:
Callback enters:
Callback Queue
What is Callback Queue?
The Callback Queue stores completed asynchronous callbacks.
Example:
setTimeout(
function()
{
console.log("Timer");
},
2000
);
After timer completion:
Callback Queue
↓
console.log("Timer")
What is the Event Loop?
The Event Loop continuously checks:
Is Call Stack Empty?
If YES:
Move Callback Queue Task
to Call Stack
Event Loop Workflow
Call Stack Empty?
↓
YES
↓
Take First Callback
from Queue
↓
Move to Stack
↓
Execute
Complete Example
console.log("Start");
setTimeout(
function()
{
console.log("Timer");
},
0
);
console.log("End");
Output:
Start
End
Timer
Why Doesn't Timer Execute First?
Even though delay is:
0
The callback still goes through:
Web API
↓
Callback Queue
↓
Event Loop
↓
Call Stack
Therefore:
Start
End
Timer
Understanding Promises
Promises use a different queue.
Example:
console.log("Start");
Promise.resolve()
.then(
function()
{
console.log("Promise");
}
);
console.log("End");
Output:
Start
End
Promise
Microtask Queue
Promises are placed in:
Microtask Queue
which has higher priority.
Queues in JavaScript
Microtask Queue
(Promises)
↓
Callback Queue
(setTimeout)
Microtasks execute first.
Example
console.log("Start");
setTimeout(
() => console.log("Timer"),
0
);
Promise.resolve()
.then(
() => console.log("Promise")
);
console.log("End");
Output:
Start
End
Promise
Timer
Why Promise Executes First
Priority:
Microtask Queue
↓
Callback Queue
Promises always execute before timers.
Complete Execution Diagram
JavaScript Code
↓
Call Stack
↓
Web APIs
↓
Callback Queue
↓
Event Loop
↓
Call Stack Again
Real-Life Example
Consider ordering food online.
Place Order
↓
Restaurant Prepares Food
↓
Continue Other Work
↓
Food Ready Notification
↓
Collect Food
This is similar to asynchronous JavaScript.
Real-World Applications
These concepts are used in:
API Calls
React Applications
Node.js Servers
Chat Applications
Banking Systems
E-Commerce Platforms
Every modern JavaScript application depends on the Event Loop.
Common Interview Questions
What is the Call Stack?
A data structure that manages function execution.
What is Event Loop?
A mechanism that moves completed asynchronous tasks into the Call Stack.
Why is JavaScript Single-Threaded?
It executes one task at a time using a single Call Stack.
Why does setTimeout(0) not execute immediately?
Because the callback must first:
Pass Through
Web APIs
↓
Callback Queue
↓
Event Loop
Which Executes First?
Promise
or
setTimeout
Answer:
Promise
because Microtask Queue has higher priority.
Best Practices
Avoid infinite recursion.
Understand asynchronous behavior.
Use Promises and Async/Await properly.
Keep Call Stack small.
Avoid blocking operations.
Advantages of Understanding JavaScript Internals
Better debugging
Improved performance
Strong interview preparation
Easier asynchronous programming
Professional JavaScript development
Conclusion
The Call Stack, Web APIs, Callback Queue, Microtask Queue, and Event Loop are the core components of JavaScript's execution model.
Understanding these concepts helps explain how JavaScript handles asynchronous operations while remaining single-threaded.
Once you master these internals, concepts like Promises, Async/Await, API calls, and framework behavior become much easier to understand.
Comments
Post a Comment