Questions 81–100 of 200 · 0 of 20 on this page marked learned
81.javascript-0081Mediummid
What are Web Workers, how do they communicate with the main thread, and what can they not do?
A Web Worker runs JavaScript on a separate thread with its own global scope, so heavy computation does not freeze the page. The main thread and the worker communicate only by messages, whose data is copied with the structured clone algorithm (or transferred). A worker cannot touch the DOM, and each worker costs memory, so use a few for real heavy work.
Full answer
Because JavaScript on a page runs on one main thread, a long computation blocks clicks, animations, and rendering. A Web Worker moves the work to another thread. It starts from a separate script file or a blob, with its own global object (self), its own event loop, and no shared variables with the page.
Communication is by message passing. The page calls worker.postMessage(data) and listens with worker.onmessage; the worker does the same in reverse with self.postMessage and self.onmessage. Data is copied with the structured clone algorithm, so objects are duplicated, not shared, and functions or DOM nodes cannot be sent. For large binary data, a transferable ArrayBuffer moves without copying. Shared memory is possible with SharedArrayBuffer and Atomics under special security requirements.
What a worker cannot do: it cannot read or change the DOM, and it has no window or document. It can use fetch, timers, IndexedDB, WebSocket, crypto, and importScripts or module imports. Errors in a worker surface through its error event on the main thread. worker.terminate() stops it at once from the outside, and self.close() from the inside.
When to use them: parsing a large file, image processing, encryption, search indexing, or any task over about 50 ms. They are not helpful for waiting on network requests, as those already do not block. Message passing has a cost, and each worker uses its own memory, so a small pool is usually better than dozens.
Dedicated workers serve one page. Shared workers serve several tabs, and service workers sit between the page and the network, which is a separate topic.
Node.js has worker_threads, which follows the same ideas with different names. The code below uses it, because it can be run here.
javascript
const { Worker } = require('node:worker_threads');
const workerSource = `
const { parentPort } = require('node:worker_threads');
parentPort.on('message', (job) => {
if (job.type === 'sum') {
let total = 0;
for (let i = 1; i <= job.limit; i++) total += i % 7;
parentPort.postMessage({ type: 'result', total, echo: job.label });
} else if (job.type === 'fail') {
throw new Error('worker crashed on purpose');
}
});
`;
const worker = new Worker(workerSource, { eval: true });
const events = [];
worker.on('message', (message) => {
events.push(`worker replied: ${message.echo} = ${message.total}`);
console.log(events.join('\n'));
worker.postMessage({ type: 'fail' });
});
worker.on('error', (error) => {
console.log('error event on the main thread:', error.message);
});
worker.on('exit', (code) => {
console.log('worker exited with code', code);
});
const original = { label: 'sum of i mod 7 over 300 million values', limit: 300_000_000, type: 'sum' };
worker.postMessage(original);
original.label = 'changed after sending'; // the worker received a copy, so this has no effect
setTimeout(() => events.push('main thread still free: timer fired'), 20);
events.push('message sent, main thread continues');
Run with Node.js v24.22.1 as js-81.js; two runs gave identical output.
Output:
message sent, main thread continues
main thread still free: timer fired
worker replied: sum of i mod 7 over 300 million values = 900000003
error event on the main thread: worker crashed on purpose
worker exited with code 1
Key points
A worker runs on another thread with its own global scope and event loop.
Communication is by postMessage; data is copied (structured clone) or transferred.
Workers cannot access the DOM or window.
Use workers for tasks over about 50 ms; they do not help with waiting on I/O.
Terminate unused workers; each one costs memory.
Common mistakes
Trying to use document or window inside a worker.
Sending a function or DOM node in a message and getting a DataCloneError.
Starting a new worker for every small task, so startup and memory cost outweigh the benefit.
Forgetting to terminate workers that are no longer needed.
Follow-ups
How would you build a small pool of workers and queue tasks?
What is the difference between a dedicated worker, a shared worker, and a service worker?
How can a worker and the main thread share memory safely?
Tips
Say that the benefit is keeping the main thread free, not making the computation itself faster.
Mention structured clone and transfer for message data.
Give the rough threshold of 50 ms for when a worker is worth it.
82.javascript-0082Mediummid
Implement an EventEmitter class with on, once, off, and emit, and explain the edge cases.
An event emitter keeps a map from event names to arrays of listeners. on adds a listener, off removes one, once wraps a listener so it removes itself after the first call, and emit calls each listener with the arguments. Edge cases include removing a listener during emit, listeners added during emit, an off call for a once listener, and an unhandled error event.
Full answer
The observer pattern lets one part of a program announce events while others react, without the announcer knowing who is listening. An event emitter is the usual building block, and writing one is a common interview exercise.
The design is a Map from event name to an array of listener functions. on(name, fn) pushes the function and returns this so calls can be chained. off(name, fn) removes the listener. emit(name, ...args) calls every listener in order with this set to the emitter and returns true if there was at least one listener.
once(name, fn) registers a wrapper that first removes itself and then calls the original. The wrapper keeps a reference to the original, so off(name, fn) can still remove a once listener before it fires.
Edge cases that interviewers look for:
Removing or adding listeners during emit. Iterating over the live array would skip or repeat listeners, so emit iterates over a copy.
A listener that throws. Decide whether the error stops the other listeners (the simple version lets it propagate) and document it.
Node's convention that emitting 'error' with no listener throws the error instead of silently ignoring it.
The same function added twice, which is called twice and needs two off calls.
Memory leaks from listeners that are never removed. Node warns after ten listeners per event for this reason.
Order: listeners run in the order they were added, and prependListener adds one at the front.
A return value from on that removes the listener, like const stop = emitter.on(...), is a common convenience.
javascript
class EventEmitter {
#listeners = new Map();
on(name, listener) {
const list = this.#listeners.get(name) ?? [];
list.push(listener);
this.#listeners.set(name, list);
return this;
}
off(name, listener) {
const list = this.#listeners.get(name);
if (!list) return this;
const index = list.findIndex((item) => item === listener || item.original === listener);
if (index !== -1) list.splice(index, 1);
if (list.length === 0) this.#listeners.delete(name);
return this;
}
once(name, listener) {
const wrapper = (...args) => {
this.off(name, wrapper);
return listener.apply(this, args);
};
wrapper.original = listener;
return this.on(name, wrapper);
}
emit(name, ...args) {
const list = this.#listeners.get(name);
if (!list || list.length === 0) {
if (name === 'error') throw args[0] instanceof Error ? args[0] : new Error('Unhandled error event');
return false;
}
for (const listener of [...list]) listener.apply(this, args);
return true;
}
listenerCount(name) {
return this.#listeners.get(name)?.length ?? 0;
}
}
const emitter = new EventEmitter();
const log = [];
const greet = (name) => log.push(`hello ${name}`);
emitter.on('greet', greet).on('greet', (name) => log.push(`welcome ${name}`));
emitter.once('greet', (name) => log.push(`first time only for ${name}`));
console.log(emitter.emit('greet', 'Asha'), emitter.emit('greet', 'Ravi'), emitter.emit('nobody'));
console.log(log);
emitter.off('greet', greet);
log.length = 0;
emitter.emit('greet', 'Meera');
console.log(log, emitter.listenerCount('greet'));
const cancelled = () => log.push('should not run');
emitter.once('ping', cancelled);
emitter.off('ping', cancelled);
console.log(emitter.emit('ping'));
const stable = new EventEmitter();
const order = [];
stable.on('x', function first() {
order.push('first');
stable.off('x', first); // removing during emit
stable.on('x', () => order.push('added during emit'));
});
stable.on('x', () => order.push('second'));
stable.emit('x');
stable.emit('x');
console.log(order);
try {
emitter.emit('error', new Error('boom'));
} catch (error) {
console.log('unhandled error event:', error.message);
}
emitter.on('self', function () {
log.push(this === emitter);
});
log.length = 0;
emitter.emit('self');
console.log(log);
Run with Node.js v24.22.1 as js-82.js; two runs gave identical output.
Output:
true true false
[
'hello Asha',
'welcome Asha',
'first time only for Asha',
'hello Ravi',
'welcome Ravi'
]
[ 'welcome Meera' ] 1
false
[ 'first', 'second', 'second', 'added during emit' ]
unhandled error event: boom
[ true ]
Key points
Store listeners in a Map from event name to an array of functions.
on adds, off removes, emit calls in order and reports whether anyone listened.
once wraps the listener so it removes itself first; off must still find the original.
Emit over a copy so changes during emit do not skip or repeat listeners.
An error event without a listener should throw; leaked listeners are a memory risk.
Common mistakes
Looping over the live listener array while listeners add or remove themselves.
Making once impossible to remove because the wrapper hides the original function.
Returning undefined from on, which prevents chaining.
Silently ignoring an error event with no listener.
Follow-ups
How would you add prependListener and a maximum listener warning?
How would you support async listeners and wait for all of them?
How does the browser EventTarget differ from this design?
Tips
Write once as a wrapper that removes itself first, then calls the listener.
Mention the copy-on-emit edge case before being asked.
Return this from on, off, and once to allow chaining.
83.javascript-0083Mediummid
How would you implement Array.prototype.map, reduce, and flat yourself? What details must a correct version handle?
A correct polyfill follows the specification details: callbacks receive (value, index, array), a thisArg is respected, holes in sparse arrays are skipped, reduce without an initial value uses the first existing item and throws on an empty array, and flat takes a depth and recurses only for nested arrays. Writing them shows how the built-in methods really behave.
Full answer
Interviewers ask for these implementations to see whether a candidate knows the real behavior of the methods, not only the happy path.
For map, the method creates a result array with the same length, and for every index that exists, it calls callback.call(thisArg, value, index, array) and stores the result. Indexes that are holes in a sparse array are skipped, so the result keeps the holes. It should throw a TypeError if the callback is not a function.
For reduce, the accumulator starts as the initial value if one was given (check arguments.length or the rest parameter length, not undefined, because undefined can be a valid initial value). Without an initial value, the first existing item is used as the accumulator and the loop starts after it. On an empty array with no initial value, it throws a TypeError. The callback receives (accumulator, value, index, array).
For flat(depth = 1), walk the items and for each array item, flatten it with depth - 1, otherwise push the item. A depth of 0 copies the array shallowly, and Infinity flattens everything. Holes are removed. A recursive version is short, while an iterative version with an explicit stack avoids stack overflow on very deep arrays.
Another detail is that the real methods read length once at the start, so items appended during iteration are not visited. Define the polyfills with Object.defineProperty so they are not enumerable, otherwise for...in over arrays would show them. Only add a polyfill when the method does not already exist.
javascript
function myMap(callback, thisArg) {
if (typeof callback !== 'function') throw new TypeError(`${callback} is not a function`);
const source = this;
const length = source.length;
const result = new Array(length);
for (let i = 0; i < length; i++) {
if (i in source) result[i] = callback.call(thisArg, source[i], i, source);
}
return result;
}
function myReduce(callback, ...initial) {
if (typeof callback !== 'function') throw new TypeError(`${callback} is not a function`);
const source = this;
const length = source.length;
let index = 0;
let accumulator;
if (initial.length > 0) {
accumulator = initial[0];
} else {
while (index < length && !(index in source)) index++;
if (index >= length) throw new TypeError('Reduce of empty array with no initial value');
accumulator = source[index++];
}
for (; index < length; index++) {
if (index in source) accumulator = callback(accumulator, source[index], index, source);
}
return accumulator;
}
function myFlat(depth = 1) {
const result = [];
const walk = (list, remaining) => {
for (let i = 0; i < list.length; i++) {
if (!(i in list)) continue;
if (Array.isArray(list[i]) && remaining > 0) walk(list[i], remaining - 1);
else result.push(list[i]);
}
};
walk(this, depth);
return result;
}
const methods = { myMap, myReduce, myFlat };
for (const [name, fn] of Object.entries(methods)) {
Object.defineProperty(Array.prototype, name, { value: fn, writable: true, configurable: true, enumerable: false });
}
console.log([1, 2, 3].myMap((x) => x * 2), [1, 2, 3].map((x) => x * 2));
const sparse = [1, , 3];
console.log(sparse.myMap((x) => x + 1), sparse.map((x) => x + 1));
console.log([1, 2].myMap(function (x) { return x * this.factor; }, { factor: 10 }));
console.log([1, 2, 3, 4].myReduce((a, b) => a + b), [1, 2, 3, 4].myReduce((a, b) => a + b, 10));
console.log([].myReduce((a, b) => a + b, 'start'), [undefined].myReduce((a) => a, 'x'));
try {
[].myReduce((a, b) => a + b);
} catch (error) {
console.log(error.name + ': ' + error.message);
}
console.log([1, , 3].myReduce((a, b) => a + b));
const nested = [1, [2, [3, [4]]], , 5];
console.log(nested.myFlat(), nested.flat());
console.log(nested.myFlat(2), nested.flat(2));
console.log(nested.myFlat(Infinity), nested.myFlat(0));
const keys = [];
for (const key in [1]) keys.push(key);
console.log('enumerable keys on an array:', keys);
Run with Node.js v24.22.1 as js-83.js; two runs gave identical output.
Output:
[ 2, 4, 6 ] [ 2, 4, 6 ]
[ 2, <1 empty item>, 4 ] [ 2, <1 empty item>, 4 ]
[ 10, 20 ]
10 20
start x
TypeError: Reduce of empty array with no initial value
4
[ 1, 2, [ 3, [ 4 ] ], 5 ] [ 1, 2, [ 3, [ 4 ] ], 5 ]
[ 1, 2, 3, [ 4 ], 5 ] [ 1, 2, 3, [ 4 ], 5 ]
[ 1, 2, 3, 4, 5 ] [ 1, [ 2, [ 3, [Array] ] ], 5 ]
enumerable keys on an array: [ '0' ]
Key points
Callbacks get (value, index, array) and respect thisArg; reject non-functions with TypeError.
Skip holes in sparse arrays; keep length fixed at the start.
reduce: use the first existing item when no initial value; throw on empty input.
flat: depth defaults to 1; recurse only for arrays; Infinity flattens fully.
Define polyfills as non-enumerable and only if missing.
Common mistakes
Checking initialValue === undefined instead of how many arguments were passed.
Forgetting to skip holes, which makes sparse arrays behave differently from the built-ins.
Defining the method with plain assignment, which makes it enumerable and visible in for...in.
Flattening with recursion for any depth and not respecting the depth argument.
Follow-ups
How would you write an iterative flat that avoids stack overflow?
How would you implement filter and forEach with the same care?
Why does the specification read length once at the start?
Tips
State the edge cases before coding: holes, thisArg, empty reduce, and depth.
Use `i in source` to skip holes; it shows you know sparse arrays.
Mention defineProperty and non-enumerable methods when asked about polyfills.
84.javascript-0084Mediummid
How would you implement Function.prototype.bind yourself, including partial arguments and use with new?
bind returns a new function that calls the original with a fixed this and any pre-filled leading arguments followed by the new arguments. A faithful version also lets the bound function be used with new, in which case the fixed this is ignored and the new object inherits from the original function's prototype. The result should also keep a sensible length and name.
Full answer
bind(thisArg, ...fixedArgs) returns a new function. When the new function is called with ...laterArgs, it calls the original with this set to thisArg and the arguments [...fixedArgs, ...laterArgs].
The simple version is a closure that calls original.apply(thisArg, [...fixedArgs, ...laterArgs]). It covers most interview needs, but a complete version handles more.
When a bound function is called with new, the engine ignores the bound this. The new object should be created from the original function's prototype, so instance instanceof Original is true and instance instanceof Bound is also true. The implementation detects this with new.target (or this instanceof Bound in older code), and constructs with Reflect.construct(original, args, new.target).
Other details: throw a TypeError if the method is called on something that is not a function. The native bound function has no prototype property, and a polyfill usually points its own prototype at the original's so that instanceof works. Its length is the original length minus the number of fixed arguments (not below zero), and its name is "bound " plus the original name. A bound function cannot be rebound to a different this, which follows naturally because the closure always uses the stored thisArg.
Arrow functions ignore thisArg, as they have no this, but they can still have arguments pre-filled by bind.
The bind method is also the simplest way to create partially applied functions, which links the topic to currying.
javascript
function myBind(original, thisArg, ...fixedArgs) {
if (typeof original !== 'function') throw new TypeError('Bind must be called on a function');
function bound(...laterArgs) {
const args = [...fixedArgs, ...laterArgs];
if (new.target) return Reflect.construct(original, args, new.target === bound ? original : new.target);
return original.apply(thisArg, args);
}
bound.prototype = original.prototype; // lets instanceof work; native bound functions have no prototype property
Object.defineProperty(bound, 'name', { value: `bound ${original.name}`, configurable: true });
Object.defineProperty(bound, 'length', { value: Math.max(0, original.length - fixedArgs.length), configurable: true });
return bound;
}
function introduce(greeting, punctuation) {
return `${greeting}, I am ${this.name}${punctuation}`;
}
const person = { name: 'Asha' };
const bound = myBind(introduce, person, 'Hello');
console.log(bound('!'), introduce.bind(person, 'Hello')('!'));
console.log(bound.name, bound.length, introduce.bind(person, 'Hello').name, introduce.bind(person, 'Hello').length);
const rebound = myBind(bound, { name: 'Ravi' }, '?');
console.log(rebound());
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.sum = function () {
return this.x + this.y;
};
const BoundPoint = myBind(Point, { ignored: true }, 10);
const point = new BoundPoint(5);
console.log(point.x, point.y, point.sum(), point instanceof Point, point instanceof BoundPoint);
const NativeBound = Point.bind({ ignored: true }, 10);
const nativePoint = new NativeBound(5);
console.log(nativePoint.sum(), nativePoint instanceof Point, nativePoint instanceof NativeBound, Object.hasOwn(NativeBound, 'prototype'));
const counter = {
count: 0,
add() {
this.count += 1;
return this.count;
},
};
const detachedAdd = myBind(counter.add, counter);
const handlers = [detachedAdd, detachedAdd];
console.log(handlers.map((fn) => fn()));
const arrow = () => typeof this;
console.log(myBind(arrow, { x: 1 })());
try {
myBind('not a function', {});
} catch (error) {
console.log(error.name);
}
Run with Node.js v24.22.1 as js-84.js; two runs gave identical output.
Output:
Hello, I am Asha! Hello, I am Asha!
bound introduce 1 bound introduce 1
Hello, I am Asha?
10 5 15 true true
15 true true false
[ 1, 2 ]
object
TypeError
Key points
bind returns a closure that applies the original with a stored this and pre-filled arguments.
Later arguments are appended after the fixed ones.
With new, the bound this is ignored and the original constructor is used.
Detect construction with new.target and build with Reflect.construct.
Bound functions are named "bound x", have a reduced length, and cannot be rebound.
Common mistakes
Ignoring new, so the bound constructor creates objects with the wrong prototype.
Forgetting to append the later arguments after the fixed ones.
Using the arguments object with arrow functions inside the implementation.
Letting a second bind change this on an already bound function.
Follow-ups
How does new.target differ from this instanceof Bound for detecting construction?
Why does a bound function not have a prototype property?
How would you implement call and apply from scratch?
Tips
Write the simple closure first and then volunteer the new-support extension.
Mention name and length to show attention to the specification.
Connect bind to partial application.
85.javascript-0085Hardsenior
Implement Promise.all, Promise.allSettled, Promise.race, and Promise.any from scratch. What details do correct versions handle?
Each combinator accepts any iterable, converts every item with Promise.resolve so plain values work, and settles a new promise. all keeps results in input order and rejects at the first failure, allSettled never rejects, race follows the first settlement, and any rejects with an AggregateError only when all fail. Empty input needs special handling, and a counter, not result length, tracks completion.
Full answer
These functions are a favorite exercise because they test promises, closures, and edge cases together.
Common structure: return new Promise((resolve, reject) => { ... }), turn the input into an array with Array.from(iterable), and wrap each item with Promise.resolve(item) so plain values and thenables work.
all: keep a results array and a remaining counter. When item i fulfills, store results[i] = value (the index keeps input order, even when promises finish in another order), decrease the counter, and resolve when it reaches zero. Any rejection rejects the outer promise immediately. An empty input must resolve with [] at once, since no callback will ever run to trigger the resolve. Using results.length instead of a counter is a classic bug, because assigning to a high index makes the length jump early.
allSettled: the same shape, but both outcomes store an object, { status: 'fulfilled', value } or { status: 'rejected', reason }, and the promise never rejects.
race: attach the outer resolve and reject to every item. The first to settle wins, and later calls are ignored because a promise settles once. An empty input never settles.
any: the opposite of all. The first fulfillment resolves. Collect rejection reasons by index, and when all have rejected, reject with new AggregateError(errors, 'All promises were rejected'). An empty input rejects right away.
Other details: if the iterable itself throws while iterating, the returned promise should reject instead of throwing synchronously, and the executor already handles that when the code runs inside it. None of these cancel the other promises.
Run with Node.js v24.22.1 as js-85.js; two runs gave identical output.
Output:
all, mixed values matches native {"fulfilled":["slow","plain","fast"]}
all, one rejects matches native {"rejected":"bad"}
all, empty matches native {"fulfilled":[]}
allSettled matches native {"fulfilled":[{"status":"fulfilled","value":"ok"},{"status":"rejected","reason":"bad"}]}
race matches native {"fulfilled":"fast"}
any, one succeeds matches native {"fulfilled":"winner"}
any, all fail matches native {"rejected":["x","y"]}
any, empty matches native {"rejected":[]}
[ 1, 2 ]
{"rejected":"iterator failed"}
Key points
Wrap every item with Promise.resolve and return a new Promise.
all: results by index plus a remaining counter; empty input resolves immediately.
allSettled stores status objects and never rejects.
race passes resolve and reject to every item; any collects errors and rejects with AggregateError.
Do not use results.length to detect completion.
Common mistakes
Using results.length to decide that all promises finished.
Forgetting the empty-input case for all and any, which leaves the promise pending forever.
Pushing results in completion order instead of storing them by index.
Not wrapping items with Promise.resolve, which breaks plain values and thenables.
Follow-ups
How would you implement a version of all with a concurrency limit?
Why does race with an empty array never settle?
How would you make allSettled report timing for each promise?
Tips
Describe the index plus counter design before writing code.
Mention the empty-input edge case without being asked.
Compare your results against the built-in functions to show your tests.
86.javascript-0086Mediummid
How would you implement a deepEqual function that compares two values by content?
deepEqual compares primitives with Object.is semantics, then checks that both values have the same type and prototype, and compares arrays, plain objects, dates, regular expressions, Maps, and Sets recursively. It must handle NaN, key order, extra keys, and circular references, which a WeakMap of visited pairs prevents from looping forever.
Full answer
The built-in === compares objects by reference, so two arrays with the same content are not equal. A deep comparison walks both structures and compares the content. The design choices matter, and an interviewer will usually ask which ones were made.
Steps for a solid version:
If Object.is(a, b), return true. This handles identical references and makes NaN equal to NaN. Decide whether 0 and -0 should be equal. Object.is says they differ; many libraries treat them as equal.
If either value is not an object (or is null), return false, since the primitives were already compared.
Compare the prototypes or Object.prototype.toString tags, so an array does not equal an object with the same keys, and a Date does not equal a plain object.
For Date, compare getTime(). For RegExp, compare source and flags.
For Map and Set, compare size, then entries. Map keys that are objects need a deep search, which is slower; a simple version checks keys by reference.
For arrays and plain objects, compare the key lists (own keys, including symbols if needed) and then each value recursively. Key order should not matter for objects.
Track visited pairs in a WeakMap so circular structures finish: if the pair (a, b) is already being compared, assume it is equal.
Decide what to do with functions (compare by reference), class instances (same prototype, then own properties), and non-enumerable properties (usually ignored). Time cost is proportional to the size of the data, and deep recursion can overflow on very deep structures.
For production code, use a tested library or node:util's isDeepStrictEqual, and write the version yourself in the interview.
javascript
function deepEqual(a, b, seen = new WeakMap()) {
if (Object.is(a, b)) return true;
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
if (seen.get(a) === b) return true; // already comparing this pair: assume equal
seen.set(a, b);
if (a instanceof Date) return a.getTime() === b.getTime();
if (a instanceof RegExp) return a.source === b.source && a.flags === b.flags;
if (a instanceof Map) {
if (a.size !== b.size) return false;
for (const [key, value] of a) {
if (!b.has(key) || !deepEqual(value, b.get(key), seen)) return false;
}
return true;
}
if (a instanceof Set) {
if (a.size !== b.size) return false;
for (const value of a) if (!b.has(value)) return false;
return true;
}
const keysA = Reflect.ownKeys(a);
const keysB = Reflect.ownKeys(b);
if (keysA.length !== keysB.length) return false;
return keysA.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key], seen));
}
const checks = [
['same content, different key order', { a: 1, b: [1, 2, { c: 3 }] }, { b: [1, 2, { c: 3 }], a: 1 }, true],
['extra key', { a: 1 }, { a: 1, b: undefined }, false],
['NaN values', { n: NaN }, { n: NaN }, true],
['array versus object', [1, 2], { 0: 1, 1: 2, length: 2 }, false],
['dates', new Date('2026-01-01T00:00:00Z'), new Date('2026-01-01T00:00:00Z'), true],
['different dates', new Date(0), new Date(1), false],
['regexps', /ab+/gi, /ab+/gi, true],
['maps', new Map([['k', { v: 1 }]]), new Map([['k', { v: 1 }]]), true],
['sets', new Set([1, 2]), new Set([2, 1]), true],
['null versus object', null, {}, false],
['array order matters', [1, 2], [2, 1], false],
['zero and negative zero', 0, -0, false],
];
const nodeUtil = require('node:util');
for (const [label, x, y, expected] of checks) {
const mine = deepEqual(x, y);
console.log(label.padEnd(34), mine === expected ? 'ok' : 'WRONG', mine, '| node:util says', nodeUtil.isDeepStrictEqual(x, y));
}
const first = { name: 'loop', child: { items: [1, 2] } };
first.child.parent = first;
const second = { name: 'loop', child: { items: [1, 2] } };
second.child.parent = second;
console.log('circular structures:', deepEqual(first, second));
second.child.items.push(3);
console.log('after a change:', deepEqual(first, second));
Run with Node.js v24.22.1 as js-86.js; two runs gave identical output.
Output:
same content, different key order ok true | node:util says true
extra key ok false | node:util says false
NaN values ok true | node:util says true
array versus object ok false | node:util says false
dates ok true | node:util says true
different dates ok false | node:util says false
regexps ok true | node:util says true
maps ok true | node:util says true
sets ok true | node:util says true
null versus object ok false | node:util says false
array order matters ok false | node:util says false
zero and negative zero ok false | node:util says false
circular structures: true
after a change: false
Key points
Start with Object.is for identical references and NaN.
Compare types or prototypes so arrays, objects, and dates do not mix.
Handle Date, RegExp, Map, and Set explicitly; compare arrays and objects by keys and values.
Key order should not matter for objects.
Track visited pairs in a WeakMap to survive circular references.
Common mistakes
Comparing JSON.stringify output, which depends on key order and drops undefined and functions.
Forgetting circular references and overflowing the stack.
Treating arrays and array-like objects with the same keys as equal.
Using == or loose comparison for primitives.
Follow-ups
How would you compare two Maps whose keys are objects?
How would you compare class instances with private fields?
What are the performance risks of deepEqual in a UI render loop?
Tips
Say the design choices out loud: NaN, negative zero, key order, and prototypes.
Add the WeakMap for cycles after the main version is working.
Mention isDeepStrictEqual or a library for production use.
87.javascript-0087Hardsenior
Implement an LRU (least recently used) cache with O(1) get and put. Why does a Map work, and how does the classic linked-list design compare?
An LRU cache evicts the least recently used entry when it is full. A JavaScript Map remembers insertion order, so deleting and re-inserting a key on each use keeps the oldest entry first, giving O(1) get and put without extra structures. The classic design pairs a hash map with a doubly linked list to move nodes in O(1), and both behave the same.
Full answer
A cache keeps recent results to avoid repeated work. A capacity limit forces a rule for what to throw away, and least recently used is a common choice: the entry that has gone unused the longest is evicted first. The interface is get(key), which returns the value and marks the entry as most recently used, and put(key, value), which inserts or updates and evicts if the capacity is exceeded.
The classic answer uses two structures. A hash map from key to node gives O(1) lookup. A doubly linked list orders nodes from most to least recently used. On a hit, the node is unlinked and moved to the front in O(1), because a doubly linked list can remove a node when it holds both neighbors. On overflow, the tail node is removed, and its key is deleted from the map.
In JavaScript there is a shorter route. A Map iterates in insertion order, and delete followed by set moves a key to the end. So the most recently used key is the last one and the least recently used is map.keys().next().value. All operations are O(1) on average. This is the design most interviewers accept in JavaScript, as long as the candidate can explain why it works and describe the linked-list version.
Details to handle: get on a missing key returns undefined (or a sentinel if undefined is a valid value), updating an existing key refreshes its position without evicting, and capacity must be a positive integer. Optional extras are a time-to-live, an eviction callback, and statistics for hits and misses.
Space is O(capacity). A single instance is not safe to share between workers without extra coordination, though a single-threaded event loop avoids races in one thread.
javascript
class LRUCache {
#capacity;
#map = new Map();
constructor(capacity, onEvict = () => {}) {
if (!Number.isInteger(capacity) || capacity < 1) throw new RangeError('capacity must be a positive integer');
this.#capacity = capacity;
this.onEvict = onEvict;
}
get(key) {
if (!this.#map.has(key)) return undefined;
const value = this.#map.get(key);
this.#map.delete(key);
this.#map.set(key, value); // now the most recently used
return value;
}
put(key, value) {
if (this.#map.has(key)) this.#map.delete(key);
this.#map.set(key, value);
if (this.#map.size > this.#capacity) {
const [oldestKey, oldestValue] = this.#map.entries().next().value;
this.#map.delete(oldestKey);
this.onEvict(oldestKey, oldestValue);
}
}
keys() {
return [...this.#map.keys()]; // least to most recently used
}
}
class LinkedLRU {
constructor(capacity) {
this.capacity = capacity;
this.index = new Map();
this.head = { next: null, prev: null }; // sentinel: most recent side
this.tail = { next: null, prev: null }; // sentinel: least recent side
this.head.next = this.tail;
this.tail.prev = this.head;
}
#unlink(node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
#addFront(node) {
node.next = this.head.next;
node.prev = this.head;
this.head.next.prev = node;
this.head.next = node;
}
get(key) {
const node = this.index.get(key);
if (!node) return undefined;
this.#unlink(node);
this.#addFront(node);
return node.value;
}
put(key, value) {
const existing = this.index.get(key);
if (existing) this.#unlink(existing);
const node = existing ?? { key, value };
node.value = value;
this.#addFront(node);
this.index.set(key, node);
if (this.index.size > this.capacity) {
const last = this.tail.prev;
this.#unlink(last);
this.index.delete(last.key);
}
}
keys() {
const result = [];
for (let node = this.tail.prev; node !== this.head; node = node.prev) result.push(node.key);
return result;
}
}
const evicted = [];
const cache = new LRUCache(2, (key) => evicted.push(key));
cache.put('a', 1);
cache.put('b', 2);
console.log(cache.get('a'), cache.keys());
cache.put('c', 3); // evicts b, because a was just used
console.log(cache.get('b'), cache.keys(), evicted);
cache.put('a', 10); // update refreshes a, no eviction
console.log(cache.keys(), cache.get('a'), evicted);
try {
new LRUCache(0);
} catch (error) {
console.log(error.name);
}
function mulberry32(seed) {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const random = mulberry32(2026);
const mapVersion = new LRUCache(5);
const listVersion = new LinkedLRU(5);
let same = true;
for (let step = 0; step < 5000; step++) {
const key = Math.floor(random() * 12);
if (random() < 0.5) {
mapVersion.put(key, step);
listVersion.put(key, step);
} else if (mapVersion.get(key) !== listVersion.get(key)) {
same = false;
}
if (step % 500 === 0 && mapVersion.keys().join() !== listVersion.keys().join()) same = false;
}
console.log('Map version and linked-list version agree on 5000 random operations:', same);
Run with Node.js v24.22.1 as js-87.js; two runs gave identical output.
Output:
1 [ 'b', 'a' ]
undefined [ 'a', 'c' ] [ 'b' ]
[ 'c', 'a' ] 10 [ 'b' ]
RangeError
Map version and linked-list version agree on 5000 random operations: true
Key points
LRU evicts the entry unused for the longest time.
Classic design: hash map plus doubly linked list gives O(1) get and put.
Map insertion order makes delete then set a move-to-end operation.
Updating an existing key refreshes its position and must not evict.
Handle undefined values, capacity validation, and optionally TTL and eviction callbacks.
Common mistakes
Forgetting to refresh the key's position on a get, which turns the cache into FIFO.
Evicting when updating an existing key at full capacity.
Using an array with indexOf and splice, which makes every operation O(n).
Returning undefined for a miss when undefined is also a valid stored value, with no way to tell them apart.
Follow-ups
How would you add a time-to-live to each entry?
How would you make the cache safe to share between several workers?
How do LFU (least frequently used) and LRU differ, and when would LFU be better?
Tips
Explain the Map trick and why it gives O(1), then offer to draw the linked-list version.
Test the update case: putting an existing key must not evict anything.
Mention how misses and undefined values are handled.
88.javascript-0088Hardsenior
How does garbage collection work in JavaScript engines, and why is reference counting not used?
Engines free memory with tracing garbage collection: starting from roots such as globals and the active stack, they mark every reachable object and reclaim the rest. This handles reference cycles, which simple reference counting cannot. Modern engines are generational, run parts concurrently and incrementally, and collect young short-lived objects far more often than old ones.
Full answer
JavaScript has no explicit free. The engine decides when memory can be reclaimed. The rule is reachability: an object stays alive while some chain of references leads to it from a root. Roots are global variables, the local variables and arguments of functions currently on the call stack, and internal engine references.
The basic algorithm is mark-and-sweep. The collector marks every object reachable from the roots by walking references, then sweeps (frees) every unmarked object. Because it traces from the roots, two objects that only point to each other are collected once nothing else reaches them. Reference counting, which frees an object when its count falls to zero, fails here: the cycle keeps both counts at one forever. Old browsers that mixed counted DOM objects with script objects leaked memory this way, and modern engines do not use counting for JavaScript objects.
Real collectors are more complex, since a full mark-and-sweep pause would freeze the page. V8 uses a generational design based on the observation that most objects die young. New objects go into a small young generation that is collected often and quickly by copying survivors. Objects that survive a couple of rounds move to the old generation, which is collected less often with a mark-sweep-compact approach. Marking is done incrementally and concurrently on helper threads, with short pauses on the main thread, and compaction reduces fragmentation.
Practical consequences: allocation is cheap, but high allocation rates cause frequent young collections, so avoid creating large amounts of short-lived garbage in hot loops. The timing is not controllable, so code cannot depend on it, which is why WeakRef and finalization callbacks are unreliable for core logic. Leaks are objects that stay reachable, which is why listeners, timers, and caches are the usual suspects.
javascript
class Heap {
constructor() {
this.objects = new Map();
this.roots = new Set();
}
allocate(name, ...refs) {
this.objects.set(name, { name, refs: new Set(refs) });
return name;
}
link(from, to) {
this.objects.get(from).refs.add(to);
}
unlink(from, to) {
this.objects.get(from).refs.delete(to);
}
markAndSweep() {
const marked = new Set();
const stack = [...this.roots];
while (stack.length) {
const name = stack.pop();
if (marked.has(name) || !this.objects.has(name)) continue;
marked.add(name);
for (const ref of this.objects.get(name).refs) stack.push(ref);
}
const freed = [];
for (const name of [...this.objects.keys()]) {
if (!marked.has(name)) {
this.objects.delete(name);
freed.push(name);
}
}
return freed;
}
referenceCounts() {
const counts = new Map([...this.objects.keys()].map((name) => [name, 0]));
for (const { refs } of this.objects.values()) for (const ref of refs) counts.set(ref, (counts.get(ref) ?? 0) + 1);
for (const root of this.roots) counts.set(root, (counts.get(root) ?? 0) + 1);
return Object.fromEntries(counts);
}
}
const heap = new Heap();
heap.allocate('app');
heap.roots.add('app');
heap.allocate('cache');
heap.link('app', 'cache');
heap.allocate('user');
heap.allocate('session');
heap.link('user', 'session'); // a cycle: user and session point to each other
heap.link('session', 'user');
heap.link('app', 'user');
console.log('before:', [...heap.objects.keys()]);
console.log('collected while app still references user:', heap.markAndSweep());
heap.unlink('app', 'user');
console.log('reference counts after unlinking:', heap.referenceCounts());
console.log('counting would keep the cycle alive; mark-and-sweep frees:', heap.markAndSweep());
heap.allocate('listener');
heap.link('app', 'listener'); // forgotten reference: still reachable, so never freed
heap.allocate('bigBuffer');
heap.link('listener', 'bigBuffer');
console.log('leak candidate survives:', heap.markAndSweep(), [...heap.objects.keys()]);
heap.unlink('app', 'listener');
console.log('after removing the reference:', heap.markAndSweep());
Run with Node.js v24.22.1 as js-88.js; two runs gave identical output.
Output:
before: [ 'app', 'cache', 'user', 'session' ]
collected while app still references user: []
reference counts after unlinking: { app: 1, cache: 1, user: 1, session: 1 }
counting would keep the cycle alive; mark-and-sweep frees: [ 'user', 'session' ]
leak candidate survives: [] [ 'app', 'cache', 'listener', 'bigBuffer' ]
after removing the reference: [ 'listener', 'bigBuffer' ]
Key points
Reachability from roots decides what lives; unreachable objects are reclaimed.
Mark-and-sweep handles cycles; reference counting does not.
Engines are generational: young objects are collected often, old ones rarely.
Marking is incremental and concurrent to keep pauses short.
Timing is not controllable; leaks are objects that remain reachable.
Common mistakes
Believing JavaScript uses reference counting.
Saying that setting a variable to null frees memory immediately; it only makes the object unreachable.
Depending on the timing of garbage collection or finalizers.
Calling an unreachable cycle a leak; cycles are collected, while reachable-but-unused objects are the leaks.
Follow-ups
Why do generational collectors perform well for most programs?
What is a write barrier, and why do incremental collectors need one?
How do you trigger and observe garbage collection while debugging in Node.js?
Tips
Define reachability first, then walk through mark and sweep.
Explain the cycle case; it is the reason counting is not used.
Mention generations in one sentence and say that timing cannot be relied on.
89.javascript-0089Hardsenior
How does the browser turn HTML into pixels, and what are reflow, repaint, and layout thrashing?
The browser builds the DOM and CSSOM, combines them into a render tree, computes geometry in layout (reflow), paints pixels into layers, and composites the layers on the GPU. Changing geometry triggers layout, changing appearance triggers paint, and transform or opacity changes can often skip both. Layout thrashing is alternating DOM writes and layout reads in a loop, which forces repeated synchronous layouts.
Full answer
The rendering pipeline has these main stages. The browser parses HTML into the DOM and CSS into the CSSOM. Together they form the render tree of visible boxes with computed styles. Layout, also called reflow, calculates each box's size and position. Paint turns boxes into drawing instructions and pixels in one or more layers. Compositing combines the layers, often on the GPU, into the final frame.
What a change triggers depends on the property. Changing width, height, margin, top, font size, or adding and removing elements affects geometry and can force layout of a large part of the page, followed by paint and composite. Changing color or background only needs paint and composite. Changing transform and opacity on a layer that is already promoted can need only compositing, so these are the cheap properties for animation.
The browser batches style and layout work and normally performs it once per frame, just before painting. Reading a geometry value such as offsetHeight, getBoundingClientRect(), or scrollTop after a write forces the browser to compute layout right now so the value is correct. This is a forced synchronous layout. Layout thrashing is doing that repeatedly, for example in a loop that sets a width and then reads a height for each element, producing one layout per iteration instead of one in total.
Fixes: read all the values first and then write all the changes (batching); build changes off the document in a DocumentFragment; toggle a class instead of many inline styles; animate with transform and opacity; use requestAnimationFrame to schedule visual work at frame time; and use content-visibility or virtualization for long lists. Use the Performance panel to see the layout and paint cost.
Frames should fit in about 16 ms at 60 frames per second, which includes JavaScript, style, layout, paint, and composite work.
javascript
// A model of the browser's layout rule, not a measurement of a real browser.
class LayoutModel {
constructor() {
this.dirty = false;
this.layouts = 0;
}
write(box, height) {
box.height = height; // changing geometry marks the layout as stale
this.dirty = true;
}
read(box) {
if (this.dirty) {
this.layouts += 1; // reading forces a synchronous layout when it is stale
this.dirty = false;
}
return box.height;
}
frameEnds() {
if (this.dirty) {
this.layouts += 1; // otherwise layout runs once, just before painting
this.dirty = false;
}
}
}
const makeBoxes = () => Array.from({ length: 100 }, () => ({ height: 10 }));
function thrashing() {
const model = new LayoutModel();
const boxes = makeBoxes();
for (const box of boxes) {
model.write(box, model.read(box) + 5); // read, write, read, write ...
}
model.frameEnds();
return model.layouts;
}
function batched() {
const model = new LayoutModel();
const boxes = makeBoxes();
const heights = boxes.map((box) => model.read(box)); // all reads first
boxes.forEach((box, i) => model.write(box, heights[i] + 5)); // then all writes
model.frameEnds();
return model.layouts;
}
console.log('layouts with alternating read and write:', thrashing());
console.log('layouts with reads batched before writes:', batched());
const frames = [];
function schedule(callback) {
frames.push(callback); // stands in for requestAnimationFrame
}
const model = new LayoutModel();
const box = { height: 10 };
schedule(() => model.write(box, 50));
schedule(() => model.write(box, 80));
frames.splice(0).forEach((callback) => callback());
model.frameEnds();
console.log('two writes in one frame cost layouts:', model.layouts, '| final height:', box.height);
const cost = {
'width, height, margin': ['layout', 'paint', 'composite'],
'color, background': ['paint', 'composite'],
'transform, opacity (promoted layer)': ['composite'],
};
for (const [property, stages] of Object.entries(cost)) console.log(property.padEnd(38), '->', stages.join(' + '));
Run with Node.js v24.22.1 as js-89.js; two runs gave identical output.
Output:
layouts with alternating read and write: 100
layouts with reads batched before writes: 1
two writes in one frame cost layouts: 1 | final height: 80
width, height, margin -> layout + paint + composite
color, background -> paint + composite
transform, opacity (promoted layer) -> composite
Key points
Pipeline: DOM and CSSOM, render tree, layout, paint, composite.
Geometry changes trigger layout; appearance changes trigger paint; transform and opacity can skip both.
Reading layout values after a write forces a synchronous layout.
Layout thrashing is alternating reads and writes in a loop; batch reads before writes.
Use requestAnimationFrame, class toggles, fragments, and virtualization to reduce work.
Common mistakes
Reading offsetHeight or getBoundingClientRect inside a loop that also writes styles.
Animating top, left, or width when transform would avoid layout.
Assuming every CSS change costs the same.
Optimizing without profiling, and promoting too many elements to their own layers, which uses memory.
Follow-ups
What does the will-change property do, and what are the risks of overusing it?
How do requestAnimationFrame and requestIdleCallback differ?
Which metrics (LCP, CLS, INP) are affected by layout work?
Tips
Walk through the pipeline in order and say which stage each type of change triggers.
Define layout thrashing with the read-write loop and give the batching fix.
Mention transform and opacity for animation and the Performance panel for evidence.
90.javascript-0090Hardsenior
What is prototype pollution, how does an unsafe merge cause it, and how do you prevent it?
Prototype pollution happens when attacker-controlled keys such as __proto__ or constructor.prototype are written through an unsafe recursive merge or assignment, adding properties to Object.prototype that every object then inherits. It can flip authorization checks or break logic. Prevent it by rejecting those keys, using objects without a prototype or Maps for dictionaries, checking with Object.hasOwn, and updating vulnerable libraries.
Full answer
Every plain object inherits from Object.prototype. If an attacker can add a property there, every object in the program appears to have it. The attack needs a code path that writes to an attacker-chosen path of keys. The usual culprits are deep-merge, deep-clone, set(obj, 'a.b.c', value), and query-string parsers.
How it works: JSON.parse('{"__proto__": {"isAdmin": true}}') produces an object with an own property that is literally named __proto__. A naive merge function loops over the keys of the source. For the key __proto__, target['__proto__'] does not create a property, but reads the accessor that returns Object.prototype. The merge then recurses into it and copies isAdmin onto Object.prototype. From then on, ({}).isAdmin is true, and a check such as if (user.isAdmin) passes for users who never had the flag. The same result can come from the path constructor.prototype. The impact ranges from changed behavior, to denial of service, to remote code execution when a polluted value reaches a template engine or a child process option.
Defenses, strongest first:
Do not use unsafe recursive merge on untrusted input. Use a maintained library at a patched version.
Skip the keys __proto__, constructor, and prototype while merging or setting paths.
Read and write only own properties, with Object.hasOwn.
Use Object.create(null) or a Map for lookup tables built from user keys, so there is no prototype to pollute.
Validate input against a schema before using it.
Harden the runtime: Object.freeze(Object.prototype) early in startup, or Node.js --disable-proto=delete, which removes the __proto__ accessor. Test that your libraries still work.
Review code that handles JSON.parse output, query strings, and configuration from outside as untrusted.
Run with Node.js v24.22.1 as js-90.js; two runs gave identical output.
Output:
before: undefined
after unsafe merge, a brand new object has isAdmin: true
authorization check passes for: Asha -> true
after cleanup: undefined
via constructor.prototype: yes
after safe merge: undefined
{ a: { b: 1, c: 2 }, d: 3 }
[ '__proto__' ] null undefined
[ '__proto__' ] { isAdmin: true }
false true
Key points
Pollution writes properties onto Object.prototype, which every object inherits.
Recursive merge, clone, and set-by-path with attacker keys are the common sinks.
JSON.parse can create an own key named __proto__ that a naive merge then follows.
Block __proto__, constructor, and prototype; use hasOwn, null-prototype objects, or Maps.
Freeze the prototype or disable __proto__ as extra hardening.
Common mistakes
Writing a recursive merge or set-by-path function and trusting its input.
Checking only for the key __proto__ and missing constructor.prototype.
Using the in operator or plain property reads for authorization flags, which see inherited values.
Assuming JSON.parse protects against it; it only creates the dangerous own key.
Follow-ups
Why does Object.keys not show a polluted property while for...in would?
How can pollution of Object.prototype lead to remote code execution in a Node.js server?
What does Object.freeze(Object.prototype) break, and how would you test for it?
Tips
Explain the mechanism with the __proto__ key in JSON; it is the core of the question.
Give three defenses: key filtering, null-prototype or Map, and runtime hardening.
Say that authorization flags should be checked with hasOwn or read from a trusted structure.
91.javascript-0091Hardsenior
What is a service worker, how does its lifecycle work, and which caching strategies are common?
A service worker is a script that runs in the background between a page and the network and can intercept fetch requests, cache responses, and make a site work offline. It needs HTTPS, installs and activates in a lifecycle that waits for old pages to close, and uses strategies such as cache first, network first, and stale-while-revalidate. Version the caches and plan updates carefully.
Full answer
A service worker is a special kind of worker registered by a page with navigator.serviceWorker.register('/sw.js'). It runs in a separate context with no DOM, lives by events, and can be stopped and restarted by the browser at any time, so it must not keep state in variables. It works only on secure origins (HTTPS, with localhost allowed for development), and it controls pages within its scope.
Lifecycle: after registration, the browser downloads the script and fires install. This is where a site pre-caches its core files, with event.waitUntil(...) to keep the worker alive until the work is done. A new worker then waits while an older version still controls open pages, unless the script calls self.skipWaiting(). When it takes over, activate fires, which is the place to delete old caches, and clients.claim() lets it control open pages immediately. The browser checks for a changed sw.js file on navigation, at least every 24 hours, and a byte change starts the update.
The fetch event is the core. The handler calls event.respondWith(promise) to answer a request itself. Common strategies:
Cache first: answer from the cache and go to the network only on a miss. It suits versioned static files that never change.
Network first: try the network, and fall back to the cache when offline. It suits pages and API data that should be fresh when possible.
Stale-while-revalidate: answer from the cache immediately and fetch a fresh copy in the background for next time. It suits content where speed matters more than freshness.
Network only and cache only for special cases.
Risks: a faulty worker can serve broken pages for a long time, so versioned cache names and a tested update path matter. Do not cache responses that depend on a user's login without care, and never cache error responses by mistake.
The same pattern is also the base for push notifications and background sync.
javascript
// The strategies are written as plain functions that take a cache and a fetch function.
// In a real service worker, cache comes from caches.open(name) and fetchFn is fetch.
class MemoryCache {
#store = new Map();
async match(request) {
const stored = this.#store.get(request.url);
return stored ? stored.clone() : undefined;
}
async put(request, response) {
this.#store.set(request.url, response.clone());
}
}
const log = [];
let version = 1;
const network = async (request) => {
log.push(`network hit for ${new URL(request.url).pathname} (v${version})`);
return new Response(`content v${version}`);
};
async function cacheFirst(request, cache, fetchFn) {
const cached = await cache.match(request);
if (cached) return cached;
const fresh = await fetchFn(request);
await cache.put(request, fresh.clone());
return fresh;
}
async function networkFirst(request, cache, fetchFn) {
try {
const fresh = await fetchFn(request);
await cache.put(request, fresh.clone());
return fresh;
} catch {
const cached = await cache.match(request);
if (cached) return cached;
return new Response('offline', { status: 503 });
}
}
async function staleWhileRevalidate(request, cache, fetchFn) {
const cached = await cache.match(request);
const refresh = fetchFn(request).then((fresh) => cache.put(request, fresh.clone()));
return cached ?? (await refresh, cache.match(request));
}
(async () => {
const request = new Request('https://school.example/app.js');
const cache1 = new MemoryCache();
console.log('cache first:', await (await cacheFirst(request, cache1, network)).text());
version = 2;
console.log('cache first again:', await (await cacheFirst(request, cache1, network)).text());
const cache2 = new MemoryCache();
version = 1;
console.log('network first:', await (await networkFirst(request, cache2, network)).text());
const offline = async () => {
throw new TypeError('Failed to fetch');
};
console.log('network first offline:', await (await networkFirst(request, cache2, offline)).text());
console.log('offline with empty cache:', (await networkFirst(new Request('https://school.example/other'), cache2, offline)).status);
const cache3 = new MemoryCache();
version = 1;
console.log('stale-while-revalidate, first visit:', await (await staleWhileRevalidate(request, cache3, network)).text());
version = 2;
console.log('stale-while-revalidate, next visit:', await (await staleWhileRevalidate(request, cache3, network)).text());
await new Promise((resolve) => setTimeout(resolve, 10));
console.log('stale-while-revalidate, third visit:', await (await staleWhileRevalidate(request, cache3, network)).text());
console.log(log.length, 'network calls in total');
})();
Run with Node.js v24.22.1 as js-91.js; two runs gave identical output.
Output:
cache first: content v1
cache first again: content v1
network first: content v1
network first offline: content v1
offline with empty cache: 503
stale-while-revalidate, first visit: content v1
stale-while-revalidate, next visit: content v1
stale-while-revalidate, third visit: content v2
5 network calls in total
Key points
A service worker is an event-driven, DOM-less script between page and network; HTTPS only.
Lifecycle: install (pre-cache), waiting, activate (clean old caches).
respondWith in the fetch event lets the worker answer requests.
Version cache names and plan updates; a bad worker can persist.
Common mistakes
Keeping state in global variables of the worker, which is lost when the browser stops it.
Forgetting to version cache names and delete old ones in the activate event.
Using cache first for HTML pages, which leaves users on stale pages for a long time.
Not testing the update path, so users get stuck on an old worker.
Follow-ups
What happens to open tabs when a new service worker is installed, and what does skipWaiting change?
How would you handle a cached response that depends on the user's login state?
How do you debug and unregister a service worker during development?
Tips
Describe the lifecycle in order: register, install, wait, activate, fetch.
Name the three strategies and the type of content each suits.
Mention versioned caches and update risk; it shows production experience.
92.javascript-0092Hardsenior
What are SharedArrayBuffer and Atomics, and how do they prevent race conditions between workers?
A SharedArrayBuffer is memory that several threads can see at once, unlike a copied or transferred buffer. Plain reads and writes from different workers race and can lose updates, so Atomics provides indivisible operations (add, compareExchange, load, store) and wait and notify for synchronization. Browsers require cross-origin isolation to enable it because of speculative-execution attacks.
Full answer
Normally workers share nothing and exchange copies. A SharedArrayBuffer is different: the same memory is visible to the main thread and every worker that receives it, so reads and writes by one thread are seen by the others. This enables fast parallel algorithms, but it also brings the usual concurrency problems.
The classic problem is a lost update. The statement counter[0]++ is three steps: read, add one, write. Two threads can both read 5, both write 6, and one increment disappears. The result changes from run to run, which makes the bug hard to find.
Atomics provides operations on integer typed arrays that happen as one indivisible step. Atomics.add(view, index, value) increases a value without interleaving. Atomics.load and Atomics.store give ordered, safe reads and writes. Atomics.compareExchange sets a value only if it still holds an expected one, which is the building block for locks. Atomics.wait(view, index, expected) blocks a thread until another thread calls Atomics.notify(view, index), so a thread can sleep without spinning in a loop. Atomics.wait is not allowed on the browser main thread, where Atomics.waitAsync is available instead.
Shared memory has one more requirement in browsers. Since the Spectre attacks, SharedArrayBuffer is only available on pages that are cross-origin isolated, which means serving them with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp headers. Node.js has no such restriction.
Use shared memory only when copying is too slow, for example for large numeric arrays, WebAssembly threads, or lock-free queues. Message passing is simpler and safer for most programs.
javascript
const { Worker } = require('node:worker_threads');
const workerSource = `
const { parentPort, workerData } = require('node:worker_threads');
const view = new Int32Array(workerData.buffer);
const { mode, rounds } = workerData;
if (mode === 'atomic') {
for (let i = 0; i < rounds; i++) Atomics.add(view, 0, 1);
parentPort.postMessage('done');
} else if (mode === 'plain') {
for (let i = 0; i < rounds; i++) view[1] = view[1] + 1;
parentPort.postMessage('done');
} else if (mode === 'wait') {
Atomics.wait(view, 2, 0); // sleep while the flag at index 2 is still 0
parentPort.postMessage('woken, flag is ' + Atomics.load(view, 2));
}
`;
const run = (buffer, mode, rounds = 0) =>
new Promise((resolve, reject) => {
const worker = new Worker(workerSource, { eval: true, workerData: { buffer, mode, rounds } });
worker.once('message', resolve);
worker.once('error', reject);
});
(async () => {
const buffer = new SharedArrayBuffer(16);
const view = new Int32Array(buffer);
const workers = 4;
const rounds = 100000;
await Promise.all(Array.from({ length: workers }, () => run(buffer, 'atomic', rounds)));
console.log('atomic counter:', Atomics.load(view, 0), 'expected:', workers * rounds);
await Promise.all(Array.from({ length: workers }, () => run(buffer, 'plain', rounds)));
const plain = Atomics.load(view, 1);
console.log('plain counter never exceeds the expected value:', plain <= workers * rounds);
let finished = false;
const sleeper = run(buffer, 'wait').then((message) => {
finished = true;
return message;
});
await new Promise((resolve) => setTimeout(resolve, 50));
Atomics.store(view, 2, 7);
let woken = 0;
while (!finished) {
woken += Atomics.notify(view, 2); // returns how many sleeping threads were woken
await new Promise((resolve) => setTimeout(resolve, 5));
}
console.log('at most one worker was woken:', woken <= 1);
console.log(await sleeper);
console.log(Atomics.compareExchange(view, 3, 0, 42), view[3], Atomics.compareExchange(view, 3, 0, 99), view[3]);
console.log(buffer instanceof SharedArrayBuffer, buffer.byteLength);
})();
Run with Node.js v24.22.1 as js-92.js; two runs gave identical output.
Output:
atomic counter: 400000 expected: 400000
plain counter never exceeds the expected value: true
at most one worker was woken: true
woken, flag is 7
0 42 42 42
true 16
Key points
SharedArrayBuffer memory is visible to all threads that receive it.
counter++ is read, add, write, so concurrent increments can be lost.
Atomics operations (add, load, store, compareExchange) are indivisible.
Atomics.wait and notify let a thread sleep until another thread signals; wait is not allowed on the browser main thread.
Browsers require cross-origin isolation (COOP and COEP headers) for SharedArrayBuffer.
Common mistakes
Using counter++ on shared memory and expecting a correct total.
Calling Atomics.wait on the browser main thread, which throws.
Forgetting the cross-origin isolation headers, so SharedArrayBuffer is undefined in the browser.
Reaching for shared memory when message passing would be simpler.
Follow-ups
How would you build a mutex with Atomics.compareExchange and Atomics.wait?
What is Atomics.waitAsync, and why does the main thread need it?
Why were SharedArrayBuffers disabled in browsers in 2018 and later re-enabled?
Tips
Show the three steps of counter++ and the lost update; it makes the need for Atomics clear.
Name compareExchange as the lock primitive and wait and notify for sleeping.
Mention cross-origin isolation for the browser side.
93.javascript-0093Hardsenior
What is the Temporal API (new), and how does it fix the problems of Date? Where is it available?
Temporal is a new built-in date and time API with separate immutable types for exact instants, calendar dates, wall-clock times, zoned date-times, and durations. It reached TC39 Stage 4 in March 2026 and is scheduled for ECMAScript 2027, and shipped in Firefox 139 and Chrome 144, while Node.js 24 needs a flag. It fixes Date's mutability, zero-based months, weak time zone support, and unclear parsing.
Full answer
Date mixes several ideas in one mutable object. Temporal separates them into types that say what the value means:
Temporal.Instant is an exact point in time (a timestamp), without a time zone.
Temporal.PlainDate, PlainTime, and PlainDateTime are calendar and wall-clock values without any zone, such as a birthday or an opening time.
Temporal.ZonedDateTime is a wall-clock time in a named time zone, including daylight saving rules.
Temporal.Duration is an amount of time, such as one month and three days.
Temporal.Now gives the current time in these types.
Key improvements: all objects are immutable, so add and with return new objects. Months run from 1 to 12. Parsing accepts ISO 8601 strings only, with predictable results. Arithmetic is calendar-aware: adding one month to 31 January either clamps to the end of February or rejects, depending on the overflow option, instead of silently jumping into March. A ZonedDateTime knows about daylight saving, so adding one day keeps the same wall-clock time, while adding 24 hours moves by exact time. Comparison uses compare, and differences come from until and since with a chosen largest unit. Non-Gregorian calendars are supported through calendar options.
Status (labelled new): Temporal reached Stage 4 at the TC39 meeting in March 2026 and is planned for ECMAScript 2027. It is available in Firefox 139 and later and in Chrome and Edge 144 and later. Safari support was in a 27.3 beta at the time of writing, and Node.js 24 requires the --harmony-temporal flag. For older environments, use a polyfill and feature-detect with typeof Temporal !== 'undefined'. Check current support before relying on it in production.
For storing data, send Instant values as ISO strings with a Z, or store a ZonedDateTime with its zone name when the local meaning matters, such as a meeting that stays at 9 a.m. in its zone.
javascript
if (typeof Temporal === 'undefined') throw new Error('Temporal is not available in this runtime');
const lastDay = Temporal.PlainDate.from('2026-01-31');
console.log(lastDay.add({ months: 1 }).toString(), '(clamped to the end of February)');
try {
lastDay.add({ months: 1 }, { overflow: 'reject' });
} catch (error) {
console.log('overflow reject:', error.name);
}
const start = Temporal.PlainDate.from('2026-01-01');
const end = Temporal.PlainDate.from('2026-03-01');
console.log(start.until(end).toString(), start.until(end, { largestUnit: 'month' }).toString(), start.until(end).days);
console.log(Temporal.PlainDate.compare(start, end), start.month, start.dayOfWeek, start.daysInMonth);
const before = Temporal.ZonedDateTime.from('2026-03-07T09:00:00[America/New_York]');
console.log('plus one day: ', before.add({ days: 1 }).toString({ timeZoneName: 'never' }));
console.log('plus 24 hours: ', before.add({ hours: 24 }).toString({ timeZoneName: 'never' }));
const instant = Temporal.Instant.from('2026-01-15T10:30:00Z');
console.log(instant.toString(), instant.epochMilliseconds);
console.log(instant.toZonedDateTimeISO('Asia/Kolkata').toString({ timeZoneName: 'never' }));
console.log(instant.toZonedDateTimeISO('America/New_York').toString({ timeZoneName: 'never' }));
const original = Temporal.PlainDate.from('2026-05-05');
const changed = original.with({ day: 20 });
console.log(original.toString(), changed.toString(), original === changed);
console.log(Temporal.Duration.from({ hours: 25 }).round({ largestUnit: 'day' }).toString());
console.log(Temporal.PlainDateTime.from('2026-05-05T10:00').toZonedDateTime('Europe/London').epochMilliseconds);
try {
Temporal.PlainDate.from('2026-02-30', { overflow: 'reject' });
} catch (error) {
console.log('invalid date:', error.name);
}
Run with Node.js v24.22.1 using the --harmony-temporal flag as js-93.js; two runs gave identical output.
Output:
2026-02-28 (clamped to the end of February)
overflow reject: RangeError
P59D P2M 59
-1 1 4 31
plus one day: 2026-03-08T09:00:00-04:00
plus 24 hours: 2026-03-08T10:00:00-04:00
2026-01-15T10:30:00Z 1768473000000
2026-01-15T16:00:00+05:30
2026-01-15T05:30:00-05:00
2026-05-05 2026-05-20 false
P1DT1H
1777971600000
invalid date: RangeError
Key points
Temporal has separate immutable types: Instant, Plain types, ZonedDateTime, and Duration.
Months are 1 to 12; parsing is ISO-only and strict.
Calendar-aware arithmetic with an overflow option; daylight saving handled by ZonedDateTime.
Stage 4 in March 2026, planned for ECMAScript 2027; ships in Firefox 139 and Chrome 144.
Node.js 24 needs a flag and Safari support is only in a beta, so feature-detect and polyfill.
Common mistakes
Using Temporal in production without checking browser and runtime support or adding a polyfill.
Using PlainDateTime for a moment in time that must be exact, which has no zone and no instant.
Adding 24 hours when one calendar day was meant, around a daylight saving change.
Storing local times without the time zone name when the zone matters.
Follow-ups
When would you store an Instant, and when a ZonedDateTime?
How does Temporal handle a wall-clock time that does not exist or occurs twice during daylight saving changes?
How would you feature-detect and load a polyfill only when needed?
Tips
List the types and what each one means; the idea of "say what the value is" is the core.
Show the month overflow and the daylight saving day versus 24 hours examples.
Label the status honestly: new, with limited support, so check support and polyfill.
94.javascript-0094Hardsenior
What happens inside the engine when a function is called: execution contexts, the lexical environment, the scope chain, and the call stack?
Each function call creates an execution context pushed on the call stack. It holds a lexical environment with the function's variables and a link to the outer environment, which is fixed where the function was written. Name lookup walks this scope chain outward, which explains closures, shadowing, and hoisting. When a call returns, its context is popped, but its environment survives if a closure still references it.
Full answer
When code starts, the engine creates a global execution context. Each function call creates a new execution context and pushes it on the call stack, and returning pops it. The context at the top is the one that is running. Errors and stack traces are simply a printout of this stack.
An execution context holds the pieces needed to run a piece of code. The most important is the lexical environment, a record of the variables declared in the current scope plus a reference to the outer lexical environment. That outer link is decided when the function is defined, not when it is called, which is why JavaScript scoping is called lexical (or static). Before running the body, the engine creates the bindings in two phases: declarations are registered (var as undefined, functions with their bodies, let and const uninitialized until their line), and then code runs line by line. This is what hoisting and the temporal dead zone describe. Each block with let or const gets its own environment, which is why a let in a loop body is new every iteration.
When code reads a name, the engine looks in the current environment, then the outer one, and so on up to the global environment. This is the scope chain. The first match wins, which is shadowing, and a miss at the end is a ReferenceError. The value of this is part of the context and is decided by how the function was called, except for arrow functions, which take it from the outer environment.
Closures follow naturally. The environment of a finished call is not destroyed while a function that references it is still reachable. Only the call stack frame is popped; the environment object lives on the heap until the garbage collector finds it unreachable.
The stack has a limited size, so infinite or very deep recursion ends in a RangeError. Asynchronous callbacks start on an empty stack, which is why a stack trace inside a timer callback does not include the function that scheduled it.
javascript
const trace = () =>
new Error().stack
.split('\n')
.slice(1)
.map((line) => line.trim().match(/^at (?:async )?([\w$.<>]+)/)?.[1])
.filter((name) => name && !['Object.<anonymous>', 'Module._compile'].includes(name) && !name.startsWith('Module.') && !name.startsWith('node:'))
.slice(0, 4);
function outerCall() {
return middleCall();
}
function middleCall() {
return innerCall();
}
function innerCall() {
return trace();
}
console.log('call stack, innermost first:', outerCall());
const level = 'global';
function outer() {
const level = 'outer';
function inner() {
return level; // found in outer's environment, not in the caller's
}
return inner;
}
function caller() {
const level = 'caller';
return outer()(); // the caller's variable is never consulted
}
console.log('lexical lookup:', caller());
function makeCounter() {
let count = 0; // lives on after makeCounter returns because inner functions reference it
return {
next: () => ++count,
peek: () => count,
};
}
const a = makeCounter();
const b = makeCounter();
a.next();
a.next();
b.next();
console.log('separate environments:', a.peek(), b.peek());
function hoistingDemo() {
const before = typeof later;
var later = 1;
let result;
try {
result = tdz;
} catch (error) {
result = error.name;
}
let tdz = 2;
return [before, result];
}
console.log('creation phase effects:', hoistingDemo());
const functions = [];
for (let i = 0; i < 3; i++) functions.push(() => i);
console.log('block environment per iteration:', functions.map((fn) => fn()));
function depth() {
let n = 0;
(function recurse() {
n++;
recurse();
})();
}
try {
depth();
} catch (error) {
console.log('stack is finite:', error.name);
}
function scheduleIt() {
setTimeout(function fromTimer() {
console.log('timer trace includes the function that scheduled it:', trace().join(' ').includes('scheduleIt'));
}, 0);
}
scheduleIt();
Run with Node.js v24.22.1 as js-94.js; two runs gave identical output.
Output:
call stack, innermost first: [ 'trace', 'innerCall', 'middleCall', 'outerCall' ]
lexical lookup: outer
separate environments: 2 1
creation phase effects: [ 'undefined', 'ReferenceError' ]
block environment per iteration: [ 0, 1, 2 ]
stack is finite: RangeError
timer trace includes the function that scheduled it: false
Key points
Each call creates an execution context pushed on the call stack and popped on return.
A lexical environment holds the scope's variables and a link to the outer environment, fixed at definition.
Name lookup walks the scope chain outward; the first match wins.
Creation phase registers declarations; the execution phase runs code, which explains hoisting and the TDZ.
A returned function keeps its environment alive on the heap, which is a closure.
Common mistakes
Saying that scope depends on where a function is called, not where it is defined.
Believing the variables of a finished function are always freed; closures keep them.
Mixing up the call stack, which is runtime state, with the scope chain, which comes from the code structure.
Describing hoisting as moving code, not as registering names in the creation phase.
Follow-ups
How does the scope chain differ for a function created with new Function?
What changes about the scope and this for an arrow function?
How do async functions affect the call stack, and why do async stack traces differ?
Tips
Separate two ideas: the call stack (who called whom) and the scope chain (who contains whom).
Say "lexical" means decided where the code is written; use the caller versus outer example.
Tie closures, hoisting, and the TDZ back to the environment record.
95.javascript-0095Hardsenior
What does each of these class, this, and prototype puzzles print, and why?
Seven classic traps: a base constructor calling an overridden method before the subclass fields exist, a detached method losing this, arrow class fields binding this per instance, replacing a prototype object versus editing it, an inherited accessor without a setter blocking assignment, static methods using this as the calling class, and the constructor property being lost after replacing a prototype. Each follows from the lookup rules for this and the prototype chain.
Full answer
Puzzle 1. A base constructor runs before the subclass fields are initialized. If Base calls this.label() and Child overrides label to read a class field, the field is still undefined at that moment, because fields of a derived class are set right after super() returns. The method override is already visible, since methods live on the prototype from the start.
Puzzle 2. const f = obj.method loses the receiver. In strict code and in classes, this is undefined, so f() throws a TypeError when it reads a property. An arrow function stored in a class field avoids this, because the field initializer runs once per instance and the arrow captures that instance. The cost is one function object per instance, and the method is not on the prototype.
Puzzle 3. Editing Person.prototype.greet after creating instances affects them all, because they look the method up on the shared object when called. Assigning a new object, Person.prototype = {...}, affects only instances created afterward. Earlier instances keep a link to the old prototype object, so before instanceof Person becomes false, because instanceof checks the current Person.prototype.
Puzzle 4. If a prototype defines a getter without a setter, assigning that name on an instance does not create an own property. In sloppy mode the assignment is silently ignored, and in strict mode it throws a TypeError. By contrast, assigning to an inherited plain data property creates an own property that shadows it.
Puzzle 5. A static method is called with the class as this. Child.create() inherited from Base therefore creates a Child if it uses new this(), but a Base if it hard-codes new Base().
Puzzle 6. When you replace a function's prototype with an object literal, the new object has no own constructor, so instance.constructor falls back to Object. Restore it with constructor: Person in the literal or Object.defineProperty.
Puzzle 7. super.method() inside an object literal method uses the object's prototype, set with Object.setPrototypeOf, and it still passes the current this, so the parent method sees the child's data.
The common rule behind all of them: this is decided by how a function is called, and property reads walk the prototype chain at the time of the read.
javascript
'use strict';
// 1. Base constructor calls an overridden method
class Base {
constructor() {
this.described = this.label();
}
label() {
return 'base';
}
}
class Child extends Base {
suffix = '!';
label() {
return 'child' + this.suffix;
}
}
console.log('1:', new Child().described);
// 2. Detached method versus arrow field
class Counter {
count = 0;
incrementMethod() {
return ++this.count;
}
incrementArrow = () => ++this.count;
}
const counter = new Counter();
const { incrementMethod, incrementArrow } = counter;
console.log('2 arrow:', incrementArrow());
try {
incrementMethod();
} catch (error) {
console.log('2 method:', error.constructor.name);
}
console.log('2 methods on prototype:', Object.hasOwn(counter, 'incrementMethod'), Object.hasOwn(counter, 'incrementArrow'));
// 3. Edit versus replace the prototype
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return 'hello ' + this.name;
};
const before = new Person('Asha');
Person.prototype.greet = function () {
return 'hi ' + this.name;
};
console.log('3 edited:', before.greet());
Person.prototype = {
greet() {
return 'hey ' + this.name;
},
};
const after = new Person('Ben');
console.log('3 replaced:', before.greet(), '|', after.greet());
console.log('3 instanceof:', before instanceof Person, after instanceof Person);
// 4. Inherited accessor without a setter versus a data property
class Temperature {
get unit() {
return 'C';
}
}
Temperature.prototype.scale = 'metric';
const t = new Temperature();
try {
t.unit = 'F';
} catch (error) {
console.log('4 accessor assignment:', error.constructor.name);
}
t.scale = 'imperial';
console.log('4 data property:', t.scale, Temperature.prototype.scale, Object.hasOwn(t, 'scale'));
// 5. Static this
class Shape {
static create() {
return new this();
}
static createFixed() {
return new Shape();
}
}
class Circle extends Shape {}
console.log('5:', Circle.create().constructor.name, Circle.createFixed().constructor.name);
// 6. Lost constructor
function Car() {}
Car.prototype = { drive() {} };
console.log('6:', new Car().constructor === Object, new Car().constructor === Car);
Car.prototype = { constructor: Car, drive() {} };
console.log('6 fixed:', new Car().constructor === Car);
// 7. super in an object literal
const parent = {
describe() {
return 'parent sees ' + this.name;
},
};
const kid = {
name: 'kid',
describe() {
return super.describe() + ' via kid';
},
};
Object.setPrototypeOf(kid, parent);
console.log('7:', kid.describe());
Run with Node.js v24.22.1 as js-95.js; two runs gave identical output.
Output:
1: childundefined
2 arrow: 1
2 method: TypeError
2 methods on prototype: false true
3 edited: hi Asha
3 replaced: hi Asha | hey Ben
3 instanceof: false true
4 accessor assignment: TypeError
4 data property: imperial metric true
5: Circle Shape
6: true false
6 fixed: true
7: parent sees kid via kid
Key points
Derived-class fields are initialized after super() returns, so a base constructor sees them as undefined.
A detached method loses this; an arrow class field binds this per instance.
Editing a prototype affects existing instances; replacing the prototype object does not.
An inherited getter without a setter blocks assignment (silent in sloppy mode, TypeError in strict mode).
Static methods get the calling class as this, and a replaced prototype loses its constructor property.
Common mistakes
Calling an overridable method from a base constructor and relying on subclass state.
Passing obj.method as a callback without bind or an arrow wrapper.
Replacing Person.prototype with a literal and forgetting the constructor property.
Assuming that assigning to an inherited accessor creates an own property.
Follow-ups
Why are class fields of a derived class initialized after the super call and not before?
What are the memory and testing trade-offs of arrow functions as class fields?
How would you make a property on a prototype writable per instance when it was defined as an accessor?
Tips
Walk through each puzzle by naming the rule first: call-site this, or prototype lookup at read time.
Mention the one-function-per-instance cost of arrow fields.
State what changes between strict and sloppy mode for puzzle 4.
96.javascript-0096Hardsenior
In Node.js, in what order do process.nextTick, promise callbacks, setTimeout, and setImmediate run, and why does it depend on where they are called?
After the current operation finishes, Node runs the process.nextTick queue first, then promise microtasks, before moving on. The event loop then goes through phases: timers, pending callbacks, poll (I/O), check (setImmediate), and close callbacks. From the main script, setTimeout 0 versus setImmediate is not guaranteed, but inside an I/O callback setImmediate always runs before setTimeout 0, because the check phase follows the poll phase.
Full answer
Node.js has two kinds of queues. Microtask-like queues run between operations, and the event loop phases run in a fixed cycle.
After each callback finishes, and after the main script, Node drains process.nextTick callbacks first. Then it drains promise reactions (microtasks). If a microtask adds a nextTick, Node goes back and runs it before moving on. This is why a loop of recursive nextTick calls can starve I/O: the loop never reaches the next phase.
The event loop phases are, in order:
Timers: runs expired setTimeout and setInterval callbacks.
Pending callbacks: some deferred system callbacks.
Idle and prepare: internal.
Poll: waits for and runs I/O callbacks, such as a finished file read or incoming data. If setImmediate callbacks are queued, it does not block.
Check: runs setImmediate callbacks.
Close callbacks: for example a socket close event.
A timer with 0 ms is actually 1 ms, and it fires only when the loop reaches the timers phase and the time has passed. From the main script, the loop may start before 1 ms has passed, so setTimeout(..., 0) and setImmediate can run in either order, and it varies with machine load. Never rely on it.
Inside an I/O callback, the loop is in the poll phase. The next phase is check, so setImmediate always runs first. The timer waits for the next loop cycle. That is the one deterministic case, and the snippet shows it with fs.readFile.
The snippet also shows that inside an I/O callback, after the callback returns, nextTick comes first, then promise callbacks, and only then the immediate and the timer.
In ES modules, the main module runs inside a promise job, so promise callbacks run before nextTick callbacks queued by the main script. In CommonJS, nextTick runs first.
Practical advice: use setImmediate or a promise to yield to I/O, avoid recursive nextTick, and do not design code around the order of a 0 ms timer and an immediate in the main script.
javascript
const fs = require('node:fs');
console.log('1 main script start');
process.nextTick(() => console.log('3 nextTick from main'));
Promise.resolve().then(() => console.log('4 promise from main'));
console.log('2 main script end');
// Wait for the I/O callback, then check the order inside it.
// The timer and the immediate are scheduled from inside the I/O callback,
// where the order is guaranteed.
fs.readFile(__filename, () => {
console.log('5 I/O callback');
setTimeout(() => console.log('9 timeout 0 (next loop iteration)'), 0);
setImmediate(() => console.log('8 setImmediate (check phase)'));
process.nextTick(() => console.log('6 nextTick from I/O callback'));
Promise.resolve().then(() => console.log('7 promise from I/O callback'));
});
Run with Node.js v24.22.1 as js-96.js; two runs gave identical output.
Output:
1 main script start
2 main script end
3 nextTick from main
4 promise from main
5 I/O callback
6 nextTick from I/O callback
7 promise from I/O callback
8 setImmediate (check phase)
9 timeout 0 (next loop iteration)
Key points
nextTick queue first, then promise microtasks, after each callback and after the main script.
Main script: setTimeout 0 versus setImmediate order is not guaranteed.
Inside an I/O callback, setImmediate always runs before setTimeout 0.
Recursive nextTick can starve the loop; ESM and CommonJS differ for nextTick versus promises in the main module.
Common mistakes
Assuming setTimeout 0 always runs before setImmediate, or the reverse, from the main script.
Writing recursive process.nextTick calls that block I/O.
Thinking promises and nextTick are the same queue.
Using setImmediate and process.nextTick names as if they described when they run.
Follow-ups
Why does recursive setImmediate not starve I/O the way recursive nextTick does?
Where do the callbacks of the worker thread pool, such as fs and crypto, come back into the loop?
What does queueMicrotask do compared with process.nextTick?
Tips
State the order: nextTick, promise microtasks, then phases.
Name the one deterministic case: setImmediate before setTimeout 0 inside an I/O callback.
Warn about starvation from recursive nextTick.
97.javascript-0097Hardsenior
How do you measure JavaScript performance correctly, and what mistakes make a microbenchmark misleading?
Measure with performance.now or performance.mark and measure, not Date.now, run each case many times after a warm-up, report the median and spread rather than one run, and keep results in use so the engine cannot remove the work. Use a profiler for real bottlenecks, measure in the target environment, and treat microbenchmark results as hints, not proof.
Full answer
Use the right clock. performance.now() gives high-resolution time that never goes backward and is not affected by system clock changes. Date.now() is coarse and can jump. performance.mark and performance.measure give names to spans, and they show up in browser dev tools and in PerformanceObserver.
Why one run is not a measurement: the engine compiles code in tiers. The first calls run in an interpreter, and a hot function is later optimized. So early runs are slow, later runs are fast, and the garbage collector adds random pauses. A good method is:
Warm up: run the function several times first and discard those timings.
Repeat: take many samples, in batches if each call is very short.
Summarize with the median and a spread such as the minimum and the 90th percentile. A mean is easily pulled by one GC pause.
Compare cases in the same process, alternating them, so machine noise hits both.
Common mistakes that mislead:
Dead code elimination: if the result is never used, the engine may skip the work. Keep a result and use it, for example by adding it to a sink value and printing it at the end.
Constant inputs: the engine may fold or cache them. Use realistic, varied data.
Measuring setup together with the work, such as array creation inside the timed loop.
Timing in a dev build or with the debugger open.
Trusting a microbenchmark when the real cost is elsewhere: network, layout, or rendering. Use the browser Performance panel or node --cpu-prof to find the real hot spots first.
Timer precision limits: browsers coarsen timers for security, so measure many iterations and divide.
For user-facing code, also measure what users feel with real-user metrics such as Largest Contentful Paint and Interaction to Next Paint, not only function time.
The snippet below builds a small benchmark helper, compares two ways to sum an array, and prints only the facts that are the same on every run. Actual timings vary by machine, so they are not printed.
javascript
const { performance, PerformanceObserver } = require('node:perf_hooks');
function benchmark(fn, { warmup = 5, samples = 15, iterations = 20 } = {}) {
let sink = 0;
for (let i = 0; i < warmup; i++) sink += fn();
const times = [];
for (let s = 0; s < samples; s++) {
const start = performance.now();
for (let i = 0; i < iterations; i++) sink += fn();
times.push((performance.now() - start) / iterations);
}
times.sort((a, b) => a - b);
return {
median: times[Math.floor(times.length / 2)],
min: times[0],
p90: times[Math.floor(times.length * 0.9)],
sink,
};
}
const numbers = Array.from({ length: 100000 }, (_, i) => i % 97);
function sumLoop() {
let total = 0;
for (let i = 0; i < numbers.length; i++) total += numbers[i];
return total;
}
function sumReduce() {
return numbers.reduce((total, value) => total + value, 0);
}
console.log('both give the same result:', sumLoop() === sumReduce());
const a = benchmark(sumLoop);
const b = benchmark(sumReduce);
console.log('loop median is a positive number:', a.median > 0);
console.log('stats are ordered (min <= median <= p90):', a.min <= a.median && a.median <= a.p90);
console.log('sink keeps the work alive:', a.sink > 0 && b.sink > 0);
// mark and measure with a name, collected by an observer
const seen = [];
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) seen.push(entry.name);
});
observer.observe({ entryTypes: ['measure'] });
performance.mark('sum-start');
sumLoop();
performance.mark('sum-end');
const measure = performance.measure('sum-loop', 'sum-start', 'sum-end');
console.log('measure entry:', measure.name, measure.entryType, measure.duration >= 0);
setTimeout(() => {
console.log('observer saw:', seen);
observer.disconnect();
}, 20);
Run with Node.js v24.22.1 as js-97.js; two runs gave identical output.
Output:
both give the same result: true
loop median is a positive number: true
stats are ordered (min <= median <= p90): true
sink keeps the work alive: true
measure entry: sum-loop measure true
observer saw: [ 'sum-loop' ]
Key points
Use performance.now and mark/measure; Date.now is coarse and can jump.
Warm up, repeat many times, and report the median and spread.
Keep results in use so dead code elimination cannot remove the work.
Do not time setup, constant inputs, or debug builds.
Profile to find the real bottleneck first; microbenchmarks are hints only.
Common mistakes
Timing one call and drawing a conclusion.
Using Date.now for short intervals.
Letting the engine remove the work because the result is unused.
Optimizing a function that a profile does not show as a bottleneck.
Follow-ups
Why do JavaScript engines need a warm-up, and what is tiered compilation?
Which user-facing metrics would you track for a web page, and how do they differ from function timings?
How would you detect a performance regression automatically in continuous integration?
Tips
Describe the method: warm-up, many samples, median, same process, alternate cases.
Name dead code elimination as the main trap.
Say that profiling comes before micro-optimizing.
98.javascript-0098Hardsenior
What happens with circular imports in ES modules compared with CommonJS, and how do you avoid problems?
In CommonJS, a module that is required again during its own loading returns its partially filled exports object, so values assigned later are missing. In ES modules, imports are live bindings: functions are available early because they are hoisted, but reading a const, let, or class before its module has run throws a ReferenceError. Avoid cycles by extracting shared code, and if you cannot, access the other module only inside functions called later.
Full answer
A circular dependency means module A imports B, and B imports A, directly or through other modules. Both systems allow it, but they fail differently.
CommonJS: require runs the module code at the first call and caches its module.exports. If B requires A while A is still running, B gets whatever A has exported so far, which can be an empty object. B keeps a reference to that same object, so properties that A adds later become visible, but only if B reads them later and A did not replace module.exports with a new object. A common bug is module.exports = {...} at the end of A, which leaves B holding the old empty object. Destructuring at load time (const { x } = require('./a')) copies undefined.
ES modules: imports are live, read-only bindings, not copies. Evaluation is depth first: the engine evaluates dependencies before the importing module, and in a cycle, it enters the module that was reached first and does not wait for modules already in progress. So in a cycle, one module runs before its partner has run. The result depends on what you access:
Function declarations are hoisted and initialized when the module is linked, so calling an imported function works even before its module has run, as long as the function itself does not need uninitialized values.
const, let, and class exports are in the temporal dead zone until their line runs. Reading one earlier throws ReferenceError.
Reading inside a function that runs later, after all modules have been evaluated, works for everything.
The snippet writes small files to a temporary directory and shows both cases.
How to avoid trouble:
Remove the cycle: move the shared part into a third module that both import.
Pass dependencies as arguments, or use dependency injection.
Access the other module only inside functions, not at the top level.
Prefer function declarations for exports that other modules need early.
Use a tool such as madge or an ESLint import cycle rule to detect cycles in continuous integration.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { pathToFileURL } = require('node:url');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cycle-'));
const write = (name, text) => fs.writeFileSync(path.join(dir, name), text);
// CommonJS cycle
write('a.cjs', `
exports.early = 'set before requiring b';
const b = require('./b.cjs');
exports.late = 'set after requiring b';
console.log('CJS a done. b saw:', b.sawOfA);
`);
write('b.cjs', `
const a = require('./a.cjs');
exports.sawOfA = Object.keys(a).join(',');
console.log('CJS b done');
`);
// ES module cycle
write('a.mjs', `
import { fromB } from './b.mjs';
export const valueA = 'A';
export function getA() { return valueA; }
console.log('ESM a runs, fromB() ->', fromB());
`);
write('b.mjs', `
import { getA, valueA } from './a.mjs';
export function fromB() { return 'B sees ' + getA(); }
console.log('ESM b runs');
try {
console.log(valueA);
} catch (error) {
console.log('ESM b reading valueA too early:', error.name);
}
`);
require(path.join(dir, 'a.cjs'));
console.log('---');
import(pathToFileURL(path.join(dir, 'a.mjs')).href)
.then(() => {
fs.rmSync(dir, { recursive: true, force: true });
console.log('temporary files removed');
});
Run with Node.js v24.22.1 as js-98.js; two runs gave identical output.
Output:
CJS b done
CJS a done. b saw: early
---
ESM b runs
ESM b reading valueA too early: ReferenceError
ESM a runs, fromB() -> B sees A
temporary files removed
Key points
CommonJS returns a partial exports object for a module still loading.
Replacing module.exports after a cycle leaves the other module with a stale object.
ES module imports are live bindings; evaluation order in a cycle is depth first.
Hoisted functions work early; const, let, and class exports throw a ReferenceError before they run.
Fix by extracting shared code, using late access in functions, and detecting cycles with a tool.
Common mistakes
Replacing module.exports at the end of a module that takes part in a cycle.
Destructuring a cyclic CommonJS import at the top level.
Using const arrow functions as exports that other modules call during evaluation.
Ignoring cycles because they sometimes work, then getting a different order after a refactor.
Follow-ups
Why can a hoisted function export be called before its module has run, but a const export cannot?
How does top-level await change evaluation order in a cycle?
How would you find import cycles automatically in a large code base?
Tips
Contrast copies and partial objects in CommonJS with live bindings in ES modules.
Give the fix first: break the cycle with a shared module.
Mention tools that detect cycles.
99.javascript-0099Hardsenior
What are hidden classes (shapes) in V8, and how do they affect the performance of object property access?
Engines such as V8 give each object a hidden class, also called a shape or map, that describes its property names, their order, and where they are stored. Objects created with the same properties in the same order share one shape, which lets inline caches make property reads fast. Adding properties in different orders, deleting properties, or changing shapes at hot call sites makes code slower, so initialize objects consistently.
Full answer
JavaScript objects are dynamic: you can add and remove properties at any time. A naive implementation would store each object as a hash table, which is slow. To avoid that, engines such as V8 (Chrome and Node.js) create hidden classes. A hidden class, called a map in V8 and a shape in other engines, records which properties an object has, in which order, and at which offset each value is stored.
Objects that get the same properties in the same order share one hidden class. When you add a property, the object moves to a new hidden class through a transition from the old one. The engine keeps a tree of these transitions. So { a, b } built as a then b and another object built as b then a end up with different hidden classes, although they have the same keys.
Why it matters: inline caching. At a property access site such as point.x, the engine remembers the hidden class it saw and the offset of x. The next time, it checks the class and reads at the offset, with no lookup. A site that sees one shape is monomorphic and fast. With a few shapes it is polymorphic and somewhat slower. With many shapes it is megamorphic and falls back to slower generic lookup. Optimizing compilers also rely on stable shapes to generate tight machine code.
Practical rules:
Initialize all properties in the constructor or object literal, in the same order, and do not add them later.
Do not use delete on hot objects. Deleting a property can move the object to dictionary mode, which is a slow hash table. Set it to null or undefined instead, or use a Map for objects used as dictionaries.
Keep the type of each field stable: do not switch a number field to a string.
Do not pass objects of many different shapes through the same hot function.
Arrays have similar kinds: keep them holey-free and of one element type when you can.
Do not change code for this unless a profile shows property access as a hot spot. These are engine details that change between versions, and other engines do similar things with different names. The snippet uses V8 test functions that are enabled by a Node.js flag. They are for learning and debugging, not for production code.
javascript
// The % functions are V8 debugging helpers. They need the flag --allow-natives-syntax
// and are not standard JavaScript. Use them only to learn, never in production code.
function Point(x, y) {
this.x = x;
this.y = y;
}
const p1 = new Point(1, 2);
const p2 = new Point(3, 4);
console.log('same constructor, same shape:', %HaveSameMap(p1, p2));
const a = { x: 1, y: 2 };
const b = { y: 2, x: 1 };
const c = { x: 10, y: 20 };
console.log('literal with same order shares a shape:', %HaveSameMap(a, c));
console.log('literal with another property order:', %HaveSameMap(a, b));
const grown = { x: 1 };
grown.y = 2;
console.log('same keys, built step by step vs literal:', %HaveSameMap(grown, a));
const user = { id: 1, name: 'Asha', email: 'a@example.com' };
console.log('fast properties before delete:', %HasFastProperties(user));
delete user.id;
console.log('fast properties after delete:', %HasFastProperties(user));
const dictionary = {};
for (let i = 0; i < 2000; i++) dictionary['key' + i] = i;
console.log('object with 2000 added keys has fast properties:', %HasFastProperties(dictionary));
Run with Node.js v24.22.1 using the --allow-natives-syntax flag as js-99.js; two runs gave identical output.
Output:
same constructor, same shape: true
literal with same order shares a shape: true
literal with another property order: false
same keys, built step by step vs literal: false
fast properties before delete: true
fast properties after delete: false
object with 2000 added keys has fast properties: false
Key points
A hidden class (map or shape) stores the property names, order, and offsets of an object.
Same properties in the same order share a shape; adding a property moves to a new shape.
Inline caches remember the shape at a site, so monomorphic access is fast and megamorphic access is slow.
Initialize all fields in one order, avoid delete, and keep field types and shapes stable.
Verify with a profile before changing code; these are version-specific engine details.
Common mistakes
Adding properties to objects in different orders in different code paths.
Using delete on objects that are read in hot loops.
Mixing value types in one field, such as numbers and strings.
Rewriting working code for shapes without a profile that shows a problem.
Follow-ups
What are monomorphic, polymorphic, and megamorphic call sites?
What is dictionary mode and why is it slower?
Why do class constructors that initialize all fields help the engine?
Tips
Define shape, transition, and inline cache in plain words first.
Give three rules: same order, no delete, stable types.
Say that you would profile before changing code, and that details depend on the engine version.
100.javascript-0100Hardsenior
How would you build a small reactive state system with Proxy, where effects re-run automatically when the data they read changes?
Wrap the state in a Proxy. In the get trap, record the currently running effect as a dependency of that target and key, using a WeakMap of Maps of Sets. In the set trap, update the value with Reflect.set and, if it changed, run the effects stored for that key. Wrap nested objects lazily on read, and handle array length changes, as frameworks like Vue 3 do.
Full answer
The idea is automatic dependency tracking. An effect is a function that reads state. While it runs, every state read should register that effect as a subscriber of that exact property. When the property changes, only its subscribers run again.
Pieces:
Storage: a WeakMap from each raw target object to a Map from key to a Set of effects. A WeakMap lets the garbage collector remove the data when the target is no longer used.
activeEffect: a variable set while an effect runs, so the get trap knows who is reading.
get trap: call track(target, key) to add the active effect, then return the value with Reflect.get. If the value is an object, return a reactive proxy for it, created lazily and cached, so nested state is reactive without wrapping everything up front.
set trap: set the value with Reflect.set (which respects the receiver and setters), compare the old and new value with Object.is, and call trigger(target, key) when they differ.
effect(fn): runs fn once immediately with activeEffect set, so its reads are tracked. Run effects in a copy of the set, because running one may add or remove subscribers while you iterate.
Arrays: push writes the new index, and the array length then updates by itself, so the following write to length sees an unchanged value and would not trigger anything. When a new index is added to an array, trigger the length subscribers too.
Guard against loops: an effect that writes to state it also reads would trigger itself forever, so skip the effect that is currently running.
What this simple version leaves out: cleaning up dependencies before each re-run (so branches that are no longer taken stop subscribing), batching updates and running them asynchronously, has and ownKeys traps so in and Object.keys are reactive, deleteProperty, and computed values with caching. Vue 3 does all of these. The key point for an interview is the structure: track in get, trigger in set, and a registry keyed by target and property.
javascript
const targetMap = new WeakMap();
const proxyCache = new WeakMap();
let activeEffect = null;
function track(target, key) {
if (!activeEffect) return;
let keyMap = targetMap.get(target);
if (!keyMap) targetMap.set(target, (keyMap = new Map()));
let subscribers = keyMap.get(key);
if (!subscribers) keyMap.set(key, (subscribers = new Set()));
subscribers.add(activeEffect);
}
function trigger(target, key) {
const subscribers = targetMap.get(target)?.get(key);
if (!subscribers) return;
for (const run of [...subscribers]) {
if (run !== activeEffect) run(); // skip the effect that is running, to avoid self-loops
}
}
function effect(fn) {
const run = () => {
const previous = activeEffect;
activeEffect = run;
try {
return fn();
} finally {
activeEffect = previous;
}
};
run();
return run;
}
function reactive(raw) {
if (proxyCache.has(raw)) return proxyCache.get(raw);
const proxy = new Proxy(raw, {
get(target, key, receiver) {
track(target, key);
const value = Reflect.get(target, key, receiver);
return typeof value === 'object' && value !== null ? reactive(value) : value;
},
set(target, key, value, receiver) {
const hadKey = Object.hasOwn(target, key);
const oldValue = target[key];
const result = Reflect.set(target, key, value, receiver);
if (!hadKey || !Object.is(oldValue, value)) {
trigger(target, key);
if (Array.isArray(target) && !hadKey) trigger(target, 'length');
}
return result;
},
});
proxyCache.set(raw, proxy);
return proxy;
}
const rawUser = { name: 'Asha' };
const state = reactive({ count: 0, user: rawUser, items: [1, 2, 3] });
effect(() => console.log('count effect:', state.count));
effect(() => console.log('name effect:', state.user.name));
effect(() => console.log('items effect: length', state.items.length));
console.log('--- change count');
state.count++;
console.log('--- same value, no re-run');
state.count = 1;
console.log('--- change nested name');
state.user.name = 'Ben';
console.log('--- push to array');
state.items.push(4);
console.log('--- unrelated key does not trigger');
state.other = 'x';
console.log('--- same raw object gives the same proxy:', reactive(rawUser) === state.user);
let runs = 0;
effect(() => {
runs++;
state.count = state.count + 1; // writes what it reads; must not loop forever
});
console.log('self-writing effect ran', runs, 'time(s), count is', state.count);
Run with Node.js v24.22.1 as js-100.js; two runs gave identical output.
Output:
count effect: 0
name effect: Asha
items effect: length 3
--- change count
count effect: 1
--- same value, no re-run
--- change nested name
name effect: Ben
--- push to array
items effect: length 4
--- unrelated key does not trigger
--- same raw object gives the same proxy: true
count effect: 2
self-writing effect ran 1 time(s), count is 2
Key points
Track in the get trap: add the active effect to a WeakMap, then Map, then Set registry.
Trigger in the set trap after Reflect.set, and only when Object.is says the value changed.
Wrap nested objects lazily on read, with a cache so the same object gives the same proxy.
Arrays need extra care: adding an index changes length without a length write.
Missing in a small version: dependency cleanup, batching, has/ownKeys/delete traps, computed values.
Common mistakes
Writing to the raw object and expecting effects to run.
Skipping Reflect and breaking setters, inheritance, or receiver behavior.
Iterating the live subscriber Set while effects change it.
Not guarding against an effect that writes to its own dependency.
Follow-ups
How does Vue 3 clean up dependencies so effects stop reacting to branches that are no longer used?
How would you batch several updates and run each effect once, asynchronously?
What are the trade-offs between Proxy-based reactivity and getter and setter based reactivity as in Vue 2?
Tips
Draw the registry: WeakMap of target to Map of key to Set of effects.
Say track in get, trigger in set, and why Reflect is used.
List what is missing and name Vue 3 and MobX as production solutions.