JavaScript Engine &
Modern Language Mechanics.
An architectural masterclass deconstructing how JavaScript runs in modern engines: V8 execution contexts, the microtask turn loop, memory heap allocation, prototype delegation, Proxy metaprogramming, and multi-threaded Atomics. Featuring live interactive visual previews and compiler drills in every lesson.
When JavaScript executes, V8 creates an Execution Context containing a Variable Environment (for lexical bindings) and a Reference to outer environments. The Call Stack tracks currently running functions using LIFO (Last-In, First-Out) frame mechanics.
function computeTax(amount) {
return amount * 0.15; // Frame 3: computeTax()
}
function processOrder(order) {
const tax = computeTax(order.total); // Frame 2: processOrder()
return order.total + tax;
}
function main() {
const finalPrice = processOrder({ total: 100 }); // Frame 1: main()
console.log('Final:', finalPrice);
}
main(); // Pushes to Call Stackconsole.log('1: Sync');
// Macrotask queue (Timers)
setTimeout(() => {
console.log('4: setTimeout (Macrotask)');
}, 0);
// Microtask queue (High priority)
Promise.resolve().then(() => {
console.log('3: Promise.then (Microtask)');
});
console.log('2: Sync');
// Output: 1: Sync -> 2: Sync -> 3: Promise -> 4: setTimeoutExecutes top-level statements to completion
Drains ENTIRE queue before yielding
Runs requestAnimationFrame and paints pixels
Executes ONE task, then checks microtasks again
function createCounter() {
let privateCount = 0; // Trapped in lexical closure!
return {
increment() {
privateCount++;
return privateCount;
},
get() {
return privateCount;
}
};
}
const counter = createCounter();
counter.increment(); // 1
console.log(counter.privateCount); // undefined (Private!)const entityProto = {
getDomain() {
return 'faisalaskari.top';
}
};
const user = Object.create(entityProto);
user.name = 'Faisal';
console.log(user.name); // 'Faisal' (Own property)
console.log(user.getDomain()); // 'faisalaskari.top' (Delegated via prototype!)
console.log(user.__proto__ === entityProto); // true
console.log(entityProto.__proto__ === Object.prototype); // true// 1. ES2024: Promise.withResolvers() - Deconstruct resolve/reject!
const { promise, resolve, reject } = Promise.withResolvers();
// 2. Parallel resilient queries:
const results = await Promise.allSettled([
fetch('/api/user'),
fetch('/api/telemetry')
]);
results.forEach(res => {
if (res.status === 'fulfilled') console.log(res.value);
else console.error('Failed:', res.reason);
});Fails fast if ANY promise rejects; returns array on all success.
Waits for ALL promises; never throws; returns { status, value/reason }.
Resolves or rejects as soon as the FASTEST promise settles.
Resolves as soon as the FIRST promise succeeds (ignores rejections).
function createReactiveState(target, onMutate) {
return new Proxy(target, {
set(obj, prop, value, receiver) {
const oldVal = Reflect.get(obj, prop, receiver);
const ok = Reflect.set(obj, prop, value, receiver);
if (ok && oldVal !== value) {
onMutate(prop, value, oldVal);
}
return ok;
}
});
}class EphemeralCache {
constructor() {
this.cache = new Map();
// Registry executes callback when target object is collected by V8
this.registry = new FinalizationRegistry((key) => {
console.log('GC collected object for key:', key);
this.cache.delete(key);
});
}
set(key, obj) {
this.cache.set(key, new WeakRef(obj));
this.registry.register(obj, key);
}
get(key) {
const ref = this.cache.get(key);
return ref ? ref.deref() : undefined; // deref() returns object or undefined if collected
}
}V8 engine is prohibited from collecting the object, even when no other variables point to it. Causes memory leaks if unmanaged.
V8 GC reclaims the memory automatically when memory pressure arises. ref.deref() safely returns undefined.
// 1. Allocate shared memory (accessible by multiple threads)
const sharedBuffer = new SharedArrayBuffer(1024);
const sharedArray = new Int32Array(sharedBuffer);
// 2. Thread-safe atomic increment (prevents write collisions)
Atomics.add(sharedArray, 0, 1);
// 3. Thread sleep / notify in Worker:
// Atomics.wait(sharedArray, 0, expectedValue) -> blocks worker thread
// Atomics.notify(sharedArray, 0, 1) -> wakes up one workerasync function* streamTokens(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
yield decoder.decode(value); // Yields each chunk to UI!
}
}
// Consumer pulls with backpressure:
for await (const chunk of streamTokens(response)) {
appendChunkToDom(chunk);
}"Architecture is about making the important decisions early, before code solidification prevents modular refactoring."
// 1. Current timestamp with exact time-zone
const now = Temporal.Now.zonedDateTimeISO('Asia/Karachi');
// 2. Add duration cleanly (handles leap years and DST automatically!)
const nextWeek = now.add({ days: 7, hours: 2 });
// 3. Difference calculation
const duration = now.until(nextWeek);
console.log(duration.total({ unit: 'hours' })); // 170 hoursconst original = {
date: new Date(),
items: new Set([1, 2, 3]),
metadata: new Map([['env', 'production']])
};
// Circular reference
original.self = original;
// Native deep clone (JSON.parse crashes on circular and drops Dates/Maps!)
const clone = structuredClone(original);
console.log(clone.date instanceof Date); // true!
console.log(clone.self === clone); // true (circular preserved!)Crashes on circular references; converts Dates to strings; drops Maps, Sets, and ArrayBuffers.
Standard Web API. Preserves circular graphs, typed arrays, Maps, Sets, and Date objects faithfully.
const controller = new AbortController();
// Pass signal to fetch:
fetch('/api/heavy-data', { signal: controller.signal })
.then(res => res.json())
.catch(err => {
if (err.name === 'AbortError') console.log('Request cancelled!');
});
// Cancel in-flight request immediately:
controller.abort();Drill 01: Private State Encapsulation with Closures
Difficulty: BeginnerImplement a function createSecureCounter(initialValue) that returns an object with increment(), decrement(), and getValue() methods. The internal counter state must be private and inaccessible from the outside.
- •createSecureCounter function accepting initial number
- •increment() increases value by 1
- •decrement() decreases value by 1
- •getValue() returns current number
- •Internal state is not accessible via direct property read