0% found this document useful (0 votes)
3 views19 pages

JavaScript Engine Concepts Complete Guide

Uploaded by

Uttam Akarapu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

JavaScript Engine Concepts Complete Guide

Uploaded by

Uttam Akarapu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

📚 Complete Developer Guide

JS

JS Engine
Concepts Guide
Master Call Stack, Event Loop, Memory Heap, and Execution
Context. Understand how JavaScript really works under the
hood.

🧠 Memory Heap 📚 Call Stack 🔄 Event Loop ⚡ Task Queues

16 4 12+
Pages Core Topics Examples

SS Suresh Shrestha Share this guide! • 3/13/2026


Follow for more JavaScript content 🚀
JS Table of Contents
What You'll Learn in This Guide
{}
Overview

JS
This guide covers the internal workings of JavaScript engines. Understanding these concepts is crucial for writing performant
code and acing technical interviews.

01 The Big Picture & Memory Heap Pages 1-3


JavaScript Engine architecture overview and how memory is managed.
V8 Engine Stack vs Heap Garbage Collection

02 Execution Context Pages 4-5


Understanding the environment where JavaScript code is evaluated and executed.
Global EC Function EC Creation & Execution

03 Call Stack Pages 6-7


LIFO data structure that tracks function execution and Stack Overflow.
LIFO Single-Threaded Stack Overflow

04 Event Loop & Task Queues Pages 8-16


The mechanism that allows non-blocking operations in JavaScript.
Microtasks Macrotasks Web APIs

💡 Interview Tip
Understanding Event Loop priority is crucial! Focus on: Sync → Microtasks → Macrotasks

JS JS Engine Concepts Overview Suresh Shrestha SS


Table of Contents Follow for more JavaScript content 🚀
JS The Big Picture
JavaScript Engine Architecture
{}
Topic 1 - Part 1

JavaScript code doesn't run by magic. A JavaScript Engine (like V8 in Chrome/[Link]) handles everything. Let's visualize
the complete runtime architecture.
JS

Complete Runtime Architecture

JavaScript Engine (V8)

MEMORY HEAP CALL STACK


(where data is stored) (where code executes)
Objects, arrays, functions One thing at a time

🔄 EVENT LOOP
Coordinator between stack & task queues

Web APIs Microtask Queue Macrotask Queue


setTimeout, fetch, Promises setTimeout callbacks
DOM Events (Higher Priority) (Lower Priority)

JS JS Engine Concepts Page 1 of 16 Suresh Shrestha SS


The Big Picture Follow for more JavaScript content 🚀
JS Memory Heap
Where Data is Stored
{}
Topic 1 - Part 2

The heap is an unstructured region of memory where objects, arrays, and functions are stored. Primitives are stored in the
stack (fast, small size).
JS
Where Each Data Type Lives
[Link]

// All of these are stored in the HEAP


const user = { name: "Alice", age: 25 }; // object → heap
const nums = [1, 2, 3, 4, 5]; // array → heap
function greet() { return "Hello"; } // function → heap

// Primitives are stored in the STACK (small, fixed size)


const x = 42; // number → stack
const name = "Bob"; // string → stack
const flag = true; // boolean → stack

How It Works (Simplified)


Stack stores REFERENCES, Heap stores ACTUAL DATA

STACK (fast, small) HEAP (large, unstructured)


Variables & References Objects, Arrays, Functions

x = 42

name = "Bob"

flag = true

{ name: "Alice", age: 25 }


user → ref

nums → ref [1, 2, 3, 4, 5]

Stack: Holds references (memory addresses) to objects in the heap Heap: Actual data lives here. Garbage Collector cleans unused
memory

JS JS Engine Concepts Page 2 of 16 Suresh Shrestha SS


Memory Heap Follow for more JavaScript content 🚀
JS Garbage Collection
Automatic Memory Management

How Garbage Collection Works


{}
Topic 1 - Part 3

JS
[Link]

let user = { name: "Alice" }; // object created in heap


user = null; // reference removed

// ↑ The object { name: "Alice" } is now unreachable


// → Garbage Collector will automatically free that memory

🗑️ Key Point: When an object has no references pointing to it, it becomes "unreachable" and the Garbage Collector
automatically frees that memory. You don't need to manually free memory in JavaScript!

Memory Leak Prevention

❌ Common Memory Leaks ✅ Prevention Tips


Forgotten event listeners, timers not cleared, references in Remove event listeners, clear intervals/timeouts, avoid
closures, global variables unnecessary globals, use WeakMap/WeakSet

⚠️ Memory Leak: If you keep references to objects you no longer need, they can't be garbage collected. Always clean up
event listeners and large data structures when done!

JS JS Engine Concepts Page 3 of 16 Suresh Shrestha SS


Garbage Collection Follow for more JavaScript content 🚀
JS Execution Context
The Environment for Code Execution
{}
Topic 2 - Part 1

An Execution Context is the environment in which JavaScript code is evaluated and executed. It contains variables, scope
chain, and the this keyword.
JS

Types of Execution Context

🌍 📦 ⚠️
Global EC Function EC Eval EC
Created when script starts. Only ONE per Created every time a function is CALLED. Created inside eval(). Avoid using eval() —
program. Creates window or global. Each call gets its OWN context. security risk!

Two Phases of Execution

1️⃣ Creation Phase (Hoisting) 2️⃣ Execution Phase


Engine scans code, sets up memory. var → undefined, Code runs line by line. Variables assigned actual values.
functions → hoisted entirely. Functions called.

What Each Context Contains

📁 🔗 👆
Variable Environment Scope Chain `this` Keyword
Variables, functions, arguments Current scope + all parent scopes Depends on HOW function is called

JS JS Engine Concepts Page 4 of 16 Suresh Shrestha SS


Execution Context Follow for more JavaScript content 🚀
JS Execution
Visual Stack Example
Context

Nested Functions Example


{}
Topic 2 - Part 2

JS
[Link]

var a = 10;

function outer() {
var b = 20;
function inner() {
var c = 30;
[Link](a + b + c); // 60
}
inner();
}
outer();

Execution Context Stack Visualization

Step 1 Step 2 Step 3 Step 4-5

Global EC outer() EC inner() EC Global EC

Script starts Global EC outer() EC All done, popped

outer() called Global EC

inner() called

📚 Key: Each function call creates a new EC pushed onto the stack. When a function finishes, its EC is destroyed and popped
off. Inner functions can access outer variables via the scope chain.

JS JS Engine Concepts Page 5 of 16 Suresh Shrestha SS


Execution Context Example Follow for more JavaScript content 🚀
JS Call Stack
LIFO Data Structure for Function Tracking
{}
Topic 3 - Part 1

JS
The Call Stack is a LIFO (Last In, First Out) data structure that tracks which function is currently being executed. JavaScript
is single-threaded — one call stack, one thing at a time!

[Link]

function multiply(a, b) { return a * b; }


function square(n) { return multiply(n, n); }
function printSquare(n) {
const result = square(n);
[Link](result);
}
printSquare(5); // Output: 25

Step-by-Step Stack Visualization

Step 1 Step 2 Step 3 Step 4

main() printSquare(5) square(5) multiply(5,5)

Script starts main() printSquare(5) square(5)

printSquare called main() printSquare(5)

square called main()

Peak! 🔝

Step 5 Step 6 Step 7 Step 8

square(5) printSquare(5) main() (empty)

printSquare(5) main() printSquare done Program ends

main() square returns

multiply returns

JS JS Engine Concepts Page 6 of 16 Suresh Shrestha SS


Call Stack Follow for more JavaScript content 🚀
JS Call Stack Properties
Key Characteristics & Stack Overflow

Key Properties of the Call Stack


Property Description
{}
Topic 3 - Part 2

JS
✅ Single-threaded ONE call stack → ONE thing at a time

✅ Synchronous Executes top-to-bottom, line by line

✅ LIFO Last function in = First function out

✅ Fixed size Too many frames = Stack Overflow

✅ Blocking Long task on stack = EVERYTHING waits

Stack Overflow
[Link]

// ❌ Infinite recursion = STACK OVERFLOW


function oops() {
oops(); // calls itself forever
}
oops();// RangeError: Maximum call stack size exceeded

oops() 💥 OVERFLOW

oops()

oops() 💥 Stack Overflow!


The stack keeps growing until it hits the browser's limit. No more
... 10,000+ more
memory = crash!
oops()

main()

🚨 The Blocking Problem: A long synchronous task FREEZES the entire UI. This is exactly why we need the Event Loop and
async operations!

JS JS Engine Concepts Page 7 of 16 Suresh Shrestha SS


Call Stack Properties Follow for more JavaScript content 🚀
JS Event Loop
The Complete Runtime Architecture
{}
Topic 4 - Part 1

The Event Loop is the mechanism that allows JavaScript to perform non-blocking operations despite being single-
threaded. Here's the complete picture of how everything connects.
JS

JavaScript Runtime Architecture

JAVASCRIPT RUNTIME

CALL STACK WEB APIs


Currently (provided by Browser/[Link])
executing
code • setTimeout / setInterval
• fetch / XMLHttpRequest
▶ • DOM Events (click, scroll)
• Geolocation
• WebSockets


when done, pushes
callback to a queue

EVENT LOOP MICROTASK QUEUE ← Higher Priority

"Is the call (Promises, queueMicrotask,



stack empty?" async/await, Mutation
YES → push Observer)
next task to
call stack
MACROTASK QUEUE ← Lower Priority

(setTimeout, setInterval,
I/O, UI rendering)

JS JS Engine Concepts Page 8 of 16 Suresh Shrestha SS


Runtime Architecture Follow for more JavaScript content 🚀
JS Event Loop
The Heart of Async JavaScript
{}
Topic 4 - Part 2

The Event Loop is the mechanism that allows JavaScript to perform non-blocking operations despite being single-
threaded. It coordinates between the Call Stack and Task Queues.
JS

The Event Loop Algorithm

🔄 How the Event Loop Works

Execute Call Stack


1 Run all synchronous code completely

Is Stack Empty?
2 If not empty, keep executing. If empty, proceed.

Drain ALL Microtasks


3 Execute ALL Promises, async/await — drain entire queue!

Render UI (if needed)


4 Browser may repaint the screen

Pick ONE Macrotask


5 Execute ONE setTimeout/setInterval callback

Repeat Forever
6 Go back to step 1 ♻️

JS JS Engine Concepts Page 9of 16 Suresh Shrestha SS


Event Loop Follow for more JavaScript content 🚀
JS Example 1: setTimeout
Understanding the Basics

[Link]("1: Start");
{}
Topic 4 - Part 3

JS
[Link]

setTimeout(() => [Link]("2: Timeout"), 0);


[Link]("3: End");

OUTPUT:
1: Start → 3: End → 2: Timeout

Why? Let's Trace Through It

🔍 Step-by-Step Execution
STEP 1 [Link]("1: Start") → Output: "1: Start"

STEP 2 setTimeout → Callback sent to Web API timer (0ms) → Moves to Macrotask Queue

STEP 3 [Link]("3: End") → Output: "3: End"

STEP 4 Stack empty → Event Loop picks macrotask → Output: "2: Timeout"

After synchronous code (before Step 4):

Call Stack (empty)

Microtasks (empty)

Macrotasks [setTimeout callback] ← waiting

JS JS Engine Concepts Page 10 of 16 Suresh Shrestha SS


setTimeout Example Follow for more JavaScript content 🚀
JS Example 2: Micro vs Macro
Critical Interview Concept! 🔥

[Link]("1: Script start");


{}
Topic 4 - Part 4

JS
[Link]

setTimeout(() => {
[Link]("2: setTimeout"); // MACROTASK
}, 0);

[Link]().then(() => {
[Link]("3: Promise"); // MICROTASK
});

[Link]("4: Script end");

OUTPUT:
1: Script start
4: Script end
3: Promise ← microtask runs FIRST
2: setTimeout ← macrotask runs AFTER

After synchronous code finishes:

Microtasks [Promise callback] ← HIGHER PRIORITY ⚡

Macrotasks [setTimeout callback] ← LOWER PRIORITY

⚡ Critical Rule: ALL microtasks are drained BEFORE any macrotask runs. Promises always beat setTimeout!

🥈 Microtasks (Higher Priority) 🥉 Macrotasks (Lower Priority)


[Link]/catch/finally, async/await, queueMicrotask(), setTimeout, setInterval, setImmediate, I/O, UI rendering
MutationObserver

JS JS Engine Concepts Page 11 of 16 Suresh Shrestha SS


Microtasks vs Macrotasks Follow for more JavaScript content 🚀
JS Example 3: Complex Order
Interview Favorite! 🔥

[Link]("1");
setTimeout(() => [Link]("2"), 0);
{}
Topic 4 - Part 5

JS
[Link]

[Link]()
.then(() => {
[Link]("3");
setTimeout(() => [Link]("4"), 0);
})
.then(() => [Link]("5"));
setTimeout(() => [Link]("6"), 0);
[Link]("7");

Let's Trace Step by Step

🔍 Phase 1: Execute Synchronous Code


SYNC [Link]("1") → Output: "1"

WEB API setTimeout → cb1 goes to Macrotask Queue

MICRO [Link] → cb2 goes to Microtask Queue

WEB API setTimeout → cb3 goes to Macrotask Queue

SYNC [Link]("7") → Output: "7"

After sync code — Queue State:

Microtasks [cb2 (Promise)]

Macrotasks [cb1 ("2"), cb3 ("6")]

✅ FINAL OUTPUT:
1, 7, 3, 5, 2, 6, 4

JS JS Engine Concepts Page 12 of 16 Suresh Shrestha SS


Complex Example Follow for more JavaScript content 🚀
JS Example
Phases 2-4
3: Trace Continued

🔍 Phase 2: Drain ALL Microtasks


{}
Topic 4 - Part 6

JS
MICRO 1 Execute cb2: [Link]("3") → Output: "3"
Inside cb2: setTimeout → cb4 goes to Macrotask Queue
.then() chains → cb5 goes to Microtask Queue

MICRO 2 Execute cb5: [Link]("5") → Output: "5"


Microtask Queue now empty ✓

🔍 Phases 3-5: Execute Macrotasks (One at a Time)


MACRO 1 Execute cb1: [Link]("2") → Output: "2"

MACRO 2 Execute cb3: [Link]("6") → Output: "6"

MACRO 3 Execute cb4: [Link]("4") → Output: "4"

📝 Summary: Sync (1, 7) → Drain Microtasks (3, 5) → Macrotask (2) → Macrotask (6) → Macrotask (4). Note how "4" was added
during microtask execution but still runs last!

Key Takeaways

1️⃣ Sync First 2️⃣ Micros Beat Macros


All synchronous code runs before any async callbacks Even nested microtasks run before the next macrotask

3️⃣ One Macro at a Time 4️⃣ Order Matters


After each macrotask, check microtasks again Callbacks execute in the order they were queued

JS JS Engine Concepts Page 13 of 16 Suresh Shrestha SS


Complex Example Continued Follow for more JavaScript content 🚀
JS Example 4: async/await
How await Splits the Function

async function asyncFunc() {


[Link]("1: async start"); // synchronous!
{}
Topic 4 - Part 7

JS
[Link]

await [Link]();
// ↑ everything AFTER await goes to MICROTASK queue
[Link]("2: after await"); // microtask
}
[Link]("3: script start");
asyncFunc();
[Link]("4: script end");

OUTPUT:
3: script start
1: async start ← runs synchronously until await
4: script end
2: after await ← microtask, runs after stack is empty

⚡ Remember: await splits the function — everything BEFORE await runs synchronously. Everything AFTER await becomes a
microtask!

Example 5: Nested Microtasks


[Link]

[Link]("Start");
[Link]().then(() => {
[Link]("Microtask 1");
[Link]().then(() => [Link]("Microtask 2"));
});
setTimeout(() => [Link]("Macrotask 1"), 0);
[Link]("End");

OUTPUT:
Start → End → Microtask 1 → Microtask 2 → Macrotask 1

🔑 Critical: Nested microtasks are also drained before any macrotask. The queue must be completely empty!

JS JS Engine Concepts Page 14 of 16 Suresh Shrestha SS


async/await & Nested Microtasks Follow for more JavaScript content 🚀
JS Priority Order
Quick Reference & Cheat Sheet

Execution Priority
{}
Reference

JS
🥇 1 Synchronous Code
[Link], assignments, function calls — runs FIRST, completely

🥈 2 Microtasks
[Link]/catch/finally, async/await (after await), queueMicrotask()

🥉 3 Macrotasks
setTimeout, setInterval, setImmediate, I/O operations, UI rendering

Complete Cheat Sheet

Concept What It Is Key Point

Memory Heap Unstructured memory storage Objects, arrays, functions stored here

Call Stack LIFO stack of function calls One thing at a time (single-threaded)

Execution Context Environment for code execution Created per function call

Event Loop Coordinator between queues Sync → Microtasks → Macrotasks

Microtask Queue Promises, async/await HIGHER priority, drain completely

Macrotask Queue setTimeout, setInterval, I/O LOWER priority, one at a time

Web APIs Browser-provided async features Run outside the JS engine

JS JS Engine Concepts Page 15 of 16 Suresh Shrestha SS


Priority Order & Cheat Sheet Follow for more JavaScript content 🚀
JS Golden Rules
Key Takeaways to Remember

7 Essential Rules to Remember


{}
Best Practices

JS
1 JavaScript is single-threaded — one call stack, one thing at a time

2 Synchronous code always runs first, completely, before any async code

3 Microtasks (Promises) always run before Macrotasks (setTimeout)

4 Event loop drains ALL microtasks before picking the next macrotask

5 Promise executor runs synchronously — only .then() is async

6 Code after await is treated as a microtask

7 setTimeout(fn, 0) means "run after stack and microtasks are empty"

🎯 Interview Tip: When asked about execution order, always trace: 1) All sync code first, 2) All microtasks (drain completely),
3) One macrotask, then repeat!

JS JS Engine Concepts Page 16 of 16 Suresh Shrestha SS


Golden Rules Follow for more JavaScript content 🚀
🎉 Congratulations!

JS
Thank You!
You've Mastered JS Engine Concepts
You now understand how JavaScript really works under the
hood! Use this knowledge to write better code and ace your
technical interviews.

✅ Memory Heap ✅ Execution Context ✅ Call Stack ✅ Event Loop ✅ Task Queues

16 4 ∞
Pages Completed Core Topics Potential Unlocked

SS Suresh Shrestha Share this guide! • 3/13/2026


Follow for more JavaScript content 🚀

You might also like