What is the output of this code?
const foo = () => {
let x = 1;
return () => ++x;
};
const bar = foo();
console.log(bar(), bar());What is the output of this code?
const foo = () => {
let x = 1;
return () => ++x;
};
const bar = foo();
console.log(bar(), bar());What is the correct microtask/macrotask execution order?
setTimeout(() => console.log('A'), 0);
queueMicrotask(() => console.log('B'));
Promise.resolve().then(() => console.log('C'));
queueMicrotask(() => console.log('D'));
console.log('E');What V8 optimization is broken by this code, and what is the fix?
function Point(x, y) {
this.x = x;
this.y = y;
}
const p1 = new Point(1, 2);
const p2 = new Point(3, 4);
p2.z = 5; // added after constructionWhat is the output of this code involving Proxy and Symbol?
const obj = new Proxy({}, {
get(target, key, receiver) {
if (key === Symbol.toPrimitive) {
return (hint) => hint === 'number' ? 42 : 'obj';
}
return Reflect.get(target, key, receiver);
}
});
console.log(+obj);
console.log(`${obj}`);What does this code demonstrate about JavaScript's tail call optimization?
'use strict';
function factorial(n, acc = 1) {
if (n <= 1) return acc;
return factorial(n - 1, n * acc); // tail call
}
console.log(factorial(100000));What is the difference between structuredClone() and JSON.parse(JSON.stringify()) for deep cloning?
What is the output and why?
async function* asyncGenerator() {
yield 1;
yield 2;
throw new Error('oops');
yield 3;
}
(async () => {
for await (const value of asyncGenerator()) {
console.log(value);
}
})().catch(e => console.log('caught:', e.message));In the Temporal proposal (or date-fns/Luxon), what fundamental problem with the JavaScript Date object are they solving?
What pattern does this code implement, and what is the risk?
// db.js
let instance = null;
class Database {
constructor() {
if (instance) return instance;
this.connection = createConnection();
instance = this;
}
}
export const db = new Database();What is the purpose of WeakRef and FinalizationRegistry, introduced in ES2021?
What is Module Federation's key architectural advantage in a micro-frontend system compared to a monolithic SPA bundle?
What is the output of this code demonstrating V8's inline caching behavior with polymorphic function calls?
function getX(obj) { return obj.x; }
const a = { x: 1 };
const b = { x: 2, y: 3 };
for (let i = 0; i < 100000; i++) {
getX(i % 2 === 0 ? a : b);
}What is the output of this code demonstrating a subtle memory leak from closures retained in a long-lived event bus?
class EventBus {
#handlers = [];
on(fn) { this.#handlers.push(fn); }
}
const bus = new EventBus();
function attachComponent(largeData) {
bus.on(() => console.log(largeData.length));
}
for (let i = 0; i < 1000; i++) {
attachComponent(new Array(100000).fill(i));
}What does the Node.js libuv thread pool primarily handle, given that JavaScript itself is single-threaded?
What is the output of this code demonstrating the risk of unbounded concurrency when using Promise.all() with a large array of async I/O operations?
What is the output of this code demonstrating V8's optimization/deoptimization cycle with polymorphic argument types?
function add(a, b) { return a + b; }
for (let i = 0; i < 10000; i++) add(1, 2);
add('1', 2);What architectural trade-off does adopting a micro-frontend architecture typically introduce, compared to a single monolithic frontend?
What is the output of this code demonstrating a concurrency bug caused by shared mutable state across `Promise.all()`-driven parallel operations?
let counter = 0;
async function increment() {
const current = counter;
await new Promise(r => setTimeout(r, 10));
counter = current + 1;
}
async function main() {
await Promise.all([increment(), increment(), increment()]);
console.log(counter);
}
main();What is the primary benefit of using `Array.prototype.reduce()` with a Map or object accumulator over repeated `.find()`/`.filter()` calls for large datasets, from a performance-at-scale perspective?
What does the V8 'Scavenger' (minor GC) specifically operate on, as part of V8's generational garbage collection strategy?
What is the output of this code demonstrating async generators used for backpressure-aware streaming data processing?
async function* fetchPages() {
for (let page = 1; page <= 3; page++) {
yield await Promise.resolve(`page-${page}-data`);
}
}
async function processAll() {
const results = [];
for await (const page of fetchPages()) {
results.push(page);
}
return results;
}
processAll().then(console.log);What is a key trade-off of choosing an event-driven, single-threaded concurrency model (like Node.js) over a multi-threaded model for I/O-heavy workloads?
What is the output of this code demonstrating TypeScript-adjacent typing gotchas around structural typing with excess property checks (conceptual, evaluated as plain JS)?
What is the output of this code demonstrating the difference between microtask starvation caused by recursive Promise chains?
function recurse() {
Promise.resolve().then(recurse);
}
recurse();
setTimeout(() => console.log('timeout fired'), 0);What does 'backpressure' mean in the context of Node.js Streams, and why does it matter at scale?
What is the output of this code demonstrating a subtle bug from relying on `WeakRef.deref()` without checking for garbage collection timing?
What is the output of this code demonstrating an advanced design pattern combining the Strategy pattern with dependency injection for testability?
class PaymentProcessor {
constructor(gateway) { this.gateway = gateway; }
async pay(amount) { return this.gateway.charge(amount); }
}
const fakeGateway = { charge: async (amt) => `charged ${amt} (test)` };
const processor = new PaymentProcessor(fakeGateway);
processor.pay(50).then(console.log);What is the output of this code demonstrating how V8 handles object property access with arrays that mix element kinds (packed vs. holey, integer vs. double)?
const arr = [1, 2, 3]; // PACKED_SMI_ELEMENTS
arr.push(4.5); // becomes PACKED_DOUBLE_ELEMENTS
arr[10] = 99; // becomes HOLEY_DOUBLE_ELEMENTS (sparse)
console.log(arr.length);What is a key architectural consideration when designing shared state communication between independently deployed micro-frontends?
What is the output of this code demonstrating the risk of unbounded Promise chaining causing a stack/microtask queue buildup at scale (millions of items)?
What is the output of this code demonstrating an advanced use of `Object.defineProperty` accessor descriptors combined with Proxy traps for computed validation (metaprogramming depth)?
function createValidated(schema) {
return new Proxy({}, {
set(target, key, value) {
if (schema[key] && typeof value !== schema[key]) {
throw new TypeError(`${key} must be ${schema[key]}`);
}
target[key] = value;
return true;
}
});
}
const user = createValidated({ age: 'number' });
try {
user.age = 'thirty';
} catch (e) {
console.log(e.message);
}What is the purpose of the `SharedArrayBuffer` combined with `Atomics` in JavaScript's concurrency model?
What is the output of this code demonstrating a subtle bug in a custom Promise-based retry mechanism with exponential backoff?
async function retry(fn, retries = 3, delay = 100) {
try {
return await fn();
} catch (e) {
if (retries <= 0) throw e;
await new Promise(r => setTimeout(r, delay));
return retry(fn, retries - 1, delay * 2);
}
}
let attempts = 0;
retry(() => {
attempts++;
if (attempts < 3) throw new Error('fail');
return 'success';
}).then(console.log);What is a key difference between V8's 'Ignition' interpreter and 'TurboFan' optimizing compiler in the JIT pipeline?
What is the output of this code demonstrating a common pitfall with `AsyncLocalStorage` (Node.js) for request-scoped context in concurrent request handling?
What is the output of this code demonstrating advanced use of `Symbol.hasInstance` to customize `instanceof` behavior?
class Even {
static [Symbol.hasInstance](num) {
return Number.isInteger(num) && num % 2 === 0;
}
}
console.log(4 instanceof Even);
console.log(3 instanceof Even);What is a fundamental architectural trade-off of adopting an event-sourcing / CQRS pattern in a JavaScript/Node.js backend at scale?
What is the output of this code demonstrating a subtle issue with WeakMap-based caching when keys are primitives instead of objects?
const cache = new WeakMap();
try {
cache.set('some-string-key', 'value');
} catch (e) {
console.log(e.constructor.name);
}What is the output of this code demonstrating an advanced pattern combining generator-based coroutines with manual scheduling (a simplified cooperative multitasking model)?
function* task(name, count) {
for (let i = 0; i < count; i++) {
console.log(`${name}: ${i}`);
yield;
}
}
function scheduler(tasks) {
const iterators = tasks.map(t => t());
let done = false;
while (!done) {
done = true;
for (const it of iterators) {
const result = it.next();
if (!result.done) done = false;
}
}
}
scheduler([() => task('A', 2), () => task('B', 2)]);What is the output of this code demonstrating a performance-at-scale consideration around `JSON.stringify()` on very large object graphs in a hot request path?
What is the output of this code demonstrating the danger of `for...in` combined with prototype pollution in a legacy codebase (an advanced security/architecture concern)?
Object.prototype.polluted = 'oops';
const obj = { a: 1 };
for (const key in obj) {
console.log(key);
}
delete Object.prototype.polluted;What is a core principle of the Hexagonal Architecture (Ports and Adapters) pattern as applied to a Node.js service, and why is it valuable at scale?
What is the output of this code demonstrating a memory profiling scenario involving detached timers retaining large closures indefinitely?
function startPolling() {
const largeBuffer = new Array(1000000).fill('data');
const id = setInterval(() => {
console.log(largeBuffer.length);
}, 5000);
return id;
}
const intervalId = startPolling();
// clearInterval(intervalId) is never calledWhat is the output of this code demonstrating advanced use of `Promise.allSettled()` combined with typed result discrimination, a common pattern in resilient distributed system calls?
async function fetchAll(urls) {
const results = await Promise.allSettled(urls.map(u => Promise.resolve(u).then(x => { if (x === 'bad') throw new Error('failed'); return x; })));
return results.filter(r => r.status === 'fulfilled').map(r => r.value);
}
fetchAll(['good1', 'bad', 'good2']).then(console.log);What does 'idempotency' mean in the context of designing a distributed JavaScript/Node.js API, and why is it critical for retry logic?
What is the output of this code demonstrating a subtle bug in a custom Promise implementation's `.then()` chaining, related to microtask timing (engine-internals depth)?
What is the output of this code demonstrating an advanced closures pattern implementing private state with computed getters shared across multiple instances via a WeakMap (avoiding per-instance closure memory overhead)?
const privateState = new WeakMap();
class Counter {
constructor() { privateState.set(this, 0); }
increment() {
privateState.set(this, privateState.get(this) + 1);
return privateState.get(this);
}
}
const c1 = new Counter();
const c2 = new Counter();
c1.increment(); c1.increment();
c2.increment();
console.log(c1.increment(), c2.increment());What is a key performance-at-scale consideration when choosing between `Array` and `TypedArray` (e.g., Float64Array) for large numeric datasets in JavaScript?
What is the output of this code demonstrating an advanced concurrency pattern using a semaphore-like construct built with Promises to limit concurrent async operations?
function createSemaphore(max) {
let active = 0;
const queue = [];
return async function acquire(task) {
if (active >= max) await new Promise(resolve => queue.push(resolve));
active++;
try { return await task(); }
finally { active--; if (queue.length) queue.shift()(); }
};
}What is the output of this code demonstrating a TypeScript-adjacent gotcha around discriminated unions modeled with plain JS objects and runtime type narrowing?
function area(shape) {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'square': return shape.side ** 2;
default: throw new Error(`Unhandled shape: ${shape.kind}`);
}
}
console.log(area({ kind: 'square', side: 4 }));What is the output of this code demonstrating an advanced pattern for cancellable async operations using AbortController beyond just fetch()?
function cancellableDelay(ms, signal) {
return new Promise((resolve, reject) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('Aborted', 'AbortError'));
});
});
}
const controller = new AbortController();
cancellableDelay(1000, controller.signal).catch(e => console.log(e.name));
controller.abort();What is a key concern when designing a rate limiter for a distributed Node.js service running multiple instances behind a load balancer?
What is the output of this code demonstrating a subtle V8 performance issue caused by using `delete` on object properties in a hot loop?
function Point(x, y) { this.x = x; this.y = y; }
const points = [];
for (let i = 0; i < 1000; i++) {
const p = new Point(i, i);
if (i % 2 === 0) delete p.y;
points.push(p);
}What is the output of this code demonstrating an advanced pattern for implementing a distributed lock using an atomic Redis-like SET NX operation (conceptual, simulated in JS)?
What is the output of this code demonstrating an advanced generator-based state machine implementation for complex async workflows?
function* orderStateMachine() {
const action1 = yield 'pending';
if (action1 === 'pay') {
const action2 = yield 'paid';
if (action2 === 'ship') yield 'shipped';
}
}
const sm = orderStateMachine();
console.log(sm.next().value);
console.log(sm.next('pay').value);
console.log(sm.next('ship').value);What is a key consideration for handling 'thundering herd' problems in a distributed caching layer used by a Node.js service at scale?
What is the output of this code demonstrating request coalescing to prevent a thundering-herd cache stampede?
const inFlight = new Map();
async function getData(key, fetcher) {
if (inFlight.has(key)) return inFlight.get(key);
const promise = fetcher().finally(() => inFlight.delete(key));
inFlight.set(key, promise);
return promise;
}
let callCount = 0;
const fetcher = () => { callCount++; return Promise.resolve('data'); };
Promise.all([getData('k', fetcher), getData('k', fetcher), getData('k', fetcher)]).then(() => console.log(callCount));What is the output of this code demonstrating a subtle bug caused by relying on `Array.prototype.sort()`'s default comparator with mixed-sign numbers at scale (large dataset correctness)?
const nums = [-5, 100, -100, 5, 0];
console.log(nums.sort());What does 'eventual consistency' mean in a distributed system built with JavaScript/Node.js microservices, and what trade-off does it represent?
What is the output of this code demonstrating a subtle issue with `Array.prototype.flat()` performance on deeply nested structures at scale?
What is the output of this code demonstrating an advanced use of `Proxy` to implement a virtual/lazy-loaded module (a pattern for reducing initial bundle-parsing cost)?
function lazyModule(loader) {
let mod;
return new Proxy({}, {
get(target, prop) {
if (!mod) mod = loader();
return mod[prop];
}
});
}
const utils = lazyModule(() => { console.log('loading...'); return { double: x => x * 2 }; });
console.log('before access');
console.log(utils.double(5));What is a key challenge of implementing exactly-once message processing semantics in a Node.js service consuming from a distributed message queue (e.g., Kafka, SQS)?
What is the output of this code demonstrating an advanced closures-based dependency injection container implementation?
function createContainer() {
const registry = new Map();
return {
register(name, factory) { registry.set(name, factory); },
resolve(name) {
const factory = registry.get(name);
if (!factory) throw new Error(`No provider for ${name}`);
return factory(this);
}
};
}
const container = createContainer();
container.register('config', () => ({ env: 'prod' }));
container.register('logger', (c) => ({ log: msg => `[${c.resolve('config').env}] ${msg}` }));
console.log(container.resolve('logger').log('hello'));What is a fundamental trade-off of choosing Server-Sent Events (SSE) over WebSockets for real-time updates in a large-scale JavaScript application?
What is the output of this code demonstrating a subtle bug from mutable default state shared across module-scoped Proxy-based reactive stores in a server context handling multiple concurrent requests?
What is the output of this code demonstrating advanced usage of `FinalizationRegistry` for resource cleanup, and its inherent limitation?
What is the output of this code demonstrating a complex interaction between async/await error propagation and `Promise.any()` for implementing fallback data sources?
async function fetchFromCache() { throw new Error('cache miss'); }
async function fetchFromDB() { return 'db-data'; }
async function fetchFromCDN() { return 'cdn-data'; }
async function getData() {
try {
return await Promise.any([fetchFromCache(), fetchFromDB(), fetchFromCDN()]);
} catch (e) {
return 'all sources failed';
}
}
getData().then(console.log);What is a key consideration when designing a JavaScript SDK/library's public API to remain both tree-shakeable and backward compatible across major versions?
What is the output of this code demonstrating V8's handling of function argument count mismatches and its effect on inline cache optimization ('arguments adaptor' behavior)?
function greet(name, greeting) {
return `${greeting || 'Hello'}, ${name}`;
}
for (let i = 0; i < 5; i++) greet('A');
for (let i = 0; i < 5; i++) greet('B', 'Hi');What is the output of this code demonstrating an advanced technique combining `WeakRef` and a periodic cleanup sweep to implement a self-cleaning cache (avoiding reliance on FinalizationRegistry timing)?
What is the output of this code demonstrating a subtle bug in a hand-rolled Observable implementation regarding synchronous vs asynchronous subscriber notification (relevant to reactive/RxJS-style architectures)?
class Observable {
#subscribers = [];
subscribe(fn) { this.#subscribers.push(fn); }
next(value) { this.#subscribers.forEach(fn => fn(value)); }
}
const obs = new Observable();
const log = [];
obs.subscribe(v => log.push(`first:${v}`));
obs.next(1);
obs.subscribe(v => log.push(`second:${v}`));
obs.next(2);
console.log(log);What is a critical architectural consideration when adopting optimistic UI updates in a distributed client-server JavaScript application?
What is the output of this code demonstrating a memory profiling scenario involving retained detached DOM subtrees due to a framework's virtual DOM diffing bug (conceptual)?
What is the output of this code demonstrating advanced use of `Array.prototype.reduce()` combined with generator-based lazy pipelines to avoid creating intermediate arrays for performance at scale?
function* map(iterable, fn) {
for (const x of iterable) yield fn(x);
}
function* filter(iterable, pred) {
for (const x of iterable) if (pred(x)) yield x;
}
function take(iterable, n) {
const result = [];
for (const x of iterable) {
if (result.length >= n) break;
result.push(x);
}
return result;
}
function* naturals() { let n = 1; while (true) yield n++; }
const pipeline = take(map(filter(naturals(), x => x % 3 === 0), x => x * 2), 3);
console.log(pipeline);What is a key trade-off of using a shared-nothing architecture (each service instance has its own isolated state) versus shared-state architecture in a horizontally scaled Node.js system?
What is the output of this code demonstrating the risk of unhandled promise rejections crashing a Node.js process (a production reliability concern)?
What is the output of this code demonstrating an advanced pattern using `Proxy` combined with `Reflect` to implement a read-through cache with transparent property forwarding?
function readThroughCache(source, computeExpensive) {
const cache = new Map();
return new Proxy(source, {
get(target, prop, receiver) {
if (prop in target) return Reflect.get(target, prop, receiver);
if (!cache.has(prop)) cache.set(prop, computeExpensive(prop));
return cache.get(prop);
}
});
}
let computeCount = 0;
const obj = readThroughCache({ a: 1 }, (p) => { computeCount++; return `computed-${p}`; });
console.log(obj.a, obj.b, obj.b, computeCount);What is a key challenge of implementing zero-downtime deployments for a stateful (in-memory session) Node.js service running behind a load balancer?
What is the output of this code demonstrating a subtle bug arising from `Array.prototype.map()`'s interaction with async functions when the intention was sequential side effects (a common concurrency-model confusion)?
async function processInOrder(items) {
const log = [];
const promises = items.map(async (item) => {
await new Promise(r => setTimeout(r, Math.random() * 10));
log.push(item);
});
await Promise.all(promises);
return log;
}
processInOrder(['a', 'b', 'c']).then(result => console.log(result.length));What is a fundamental difference between horizontal scaling via Node.js's built-in `cluster` module versus scaling via multiple containerized instances behind an external load balancer?
What is the output of this code demonstrating an advanced bitwise-operation-based performance trick for flag management, and its readability trade-off?
const READ = 1, WRITE = 2, EXECUTE = 4;
let permissions = READ | WRITE;
console.log((permissions & WRITE) !== 0);
permissions &= ~WRITE;
console.log((permissions & WRITE) !== 0);What is the output of this code demonstrating a deep architectural concern: the 'N+1 query problem' manifesting in a JavaScript GraphQL resolver context?
What is the output of this code demonstrating an advanced pattern using generator delegation (`yield*`) to compose complex iterables?
function* inner() {
yield 'a';
yield 'b';
}
function* outer() {
yield 1;
yield* inner();
yield 2;
}
console.log([...outer()]);What is a key security architecture consideration when implementing Server-Side Rendering (SSR) with a JavaScript framework that shares serializable state between server and client (hydration)?
What is the output of this code demonstrating an advanced technique for detecting and breaking circular dependencies between ES modules at the architecture level?
What is the output of this code demonstrating a subtle performance regression caused by excessive object spreading in a hot reducer function (common in state-management-heavy architectures at scale)?
function reducer(state, action) {
return {
...state,
items: state.items.map(item =>
item.id === action.id ? { ...item, ...action.changes } : item
)
};
}What is the output of this code demonstrating an advanced pattern for graceful shutdown handling in a Node.js server to support zero-downtime deployments?
What is the output of this code demonstrating a subtle correctness issue with using `Date.now()` for distributed event ordering across multiple servers (clock skew)?
What is the output of this code demonstrating an advanced pattern combining `Object.freeze()` with structural sharing for efficient immutable data structures at scale?
function updateItem(list, index, newItem) {
const newList = list.slice();
newList[index] = newItem;
return Object.freeze(newList);
}
const original = Object.freeze(['a', 'b', 'c']);
const updated = updateItem(original, 1, 'B');
console.log(original[0] === updated[0], original === updated);What is a fundamental trade-off of choosing eager (server-rendered, blocking) vs. streaming Server-Side Rendering (SSR) for a large-scale JavaScript application?
What is the output of this code demonstrating an advanced technique using `Atomics.wait()` in a Worker thread for synchronous cross-thread communication (a low-level concurrency primitive)?
What is the output of this code demonstrating a subtle bug from relying on object key insertion order for numeric-like string keys in JavaScript engines?
const obj = { b: 1, 2: 'two', a: 2, 1: 'one' };
console.log(Object.keys(obj));What is a fundamental architectural consideration when choosing between a monolithic build (single large JS bundle) versus code-splitting with dynamic imports for a large-scale single-page application?
What is the output of this code demonstrating an advanced pattern using a `Proxy` revocable handle for temporarily granting and later fully revoking access to an object (security-adjacent metaprogramming)?
const { proxy, revoke } = Proxy.revocable({ secret: 42 }, {});
console.log(proxy.secret);
revoke();
try {
console.log(proxy.secret);
} catch (e) {
console.log(e.constructor.name);
}What is a key challenge of maintaining consistent TypeScript-adjacent runtime type safety when consuming a third-party JavaScript library that has incorrect or incomplete type definitions (.d.ts files)?
What is the output of this code demonstrating a subtle interaction between `async` function return values and implicit Promise wrapping when returning an already-pending Promise (Promise chain flattening)?
async function inner() {
return new Promise(resolve => setTimeout(() => resolve('inner-value'), 10));
}
async function outer() {
const result = await inner();
return result;
}
outer().then(v => console.log(v));What is a fundamental scalability consideration when a Node.js service performs CPU-intensive JSON schema validation on every incoming request at high throughput?
What is the output of this code demonstrating an advanced closure-based implementation of a 'debounced async' function that also cancels stale in-flight results (relevant to search-as-you-type architectures at scale)?
function debounceAsync(fn, delay) {
let timer, token = 0;
return function(...args) {
clearTimeout(timer);
const myToken = ++token;
return new Promise((resolve) => {
timer = setTimeout(async () => {
const result = await fn(...args);
if (myToken === token) resolve(result);
}, delay);
});
};
}What is a key architectural benefit of the 'sidecar' pattern (e.g., a proxy process alongside a Node.js service in a container) in a microservices architecture?
What is the output of this code demonstrating a deep understanding of V8's handling of large object allocations and the 'large object space' versus the regular heap?
Design a memory-efficient caching mechanism using WeakMap and explain why WeakRef alone isn't always sufficient.
How would you architect a system to avoid microtask starvation in a high-throughput Node.js application?
Compare Symbol-based property hiding with ES2022 private class fields (#field) โ when would you architecturally choose one over the other?
Explain how V8's deoptimization cycle can silently degrade performance in a long-running Node.js service, and how would you detect it in production.
How would you design a robust equality-checking utility for a large codebase that needs to handle NaN, -0, BigInt, and deeply nested objects correctly โ and why is Object.is() not always sufficient?
Critique the design trade-offs of JavaScript's automatic semicolon insertion (ASI) and explain a real production bug it can cause.
Describe a scenario where using `for...of` with `await` (async iteration) is necessary. How does it differ from `Promise.all`?
How does JavaScript's event loop interact with `while` loops? Why does a synchronous infinite loop freeze the browser?
What are some common performance pitfalls in JavaScript loops and how do you avoid them?
How would you implement a `range` function and use it with `for...of`? What is the iterator protocol?
What is the difference between a `switch` expression and a `switch` statement? (ES2025 proposal context)
What is function currying? Can you implement a simple curry function?
What is tail call optimization and does JavaScript support it?
Can closures cause memory leaks? Explain how and how to avoid it.
How would you implement a memoization function using closures?
How do closures enable the debounce and throttle patterns? Implement a simple debounce function.
What is the module pattern in JavaScript and how does it use closures and IIFEs together?
Explain how the `this` keyword is resolved in JavaScript, covering all four binding rules: default, implicit, explicit, and new binding.
How would you implement a deep equality check between two objects from scratch, without using any library?
What are the performance implications of using array methods like map(), filter(), and reduce() chained together versus a single for loop, especially on large datasets?
How does JavaScript's prototype chain relate to object property lookup, and how does it affect methods like Object.keys() and the for...in loop?
How would you implement your own version of Array.prototype.map() from scratch, and what edge cases would you need to handle?
Explain how object property descriptors work, and the difference between writable, enumerable, and configurable attributes.
Design a memoization function that caches results of expensive function calls based on their arguments, including ones that take objects as arguments.
What are the key differences between Object and Map for storing key-value data, and when would you choose one over the other?
How would you design an efficient algorithm to find the intersection of two large arrays, and what is its time complexity?
Explain a real-world scenario where misunderstanding the mutability of arrays and objects caused a bug, and how you would prevent it architecturally in a larger codebase.
How would you architect event delegation for a large, frequently-changing UI like a data table with thousands of rows?
How do unremoved event listeners cause memory leaks, especially with detached DOM nodes?
How would you build a simple pub-sub style event bus using the native EventTarget class instead of a third-party library?
How do events behave differently inside the Shadow DOM, particularly around the composed flag and event retargeting?
How would you use IntersectionObserver for something like infinite scroll or lazy-loading images, and why is it preferred over scroll-event-based approaches?
How would you use requestAnimationFrame to avoid layout thrashing when you need to read and write DOM properties repeatedly?
Why do frameworks like React use a virtual DOM and diffing instead of manipulating the real DOM directly on every state change?
How would you approach rendering a list of tens of thousands of items without crashing performance โ what is list virtualization?
What accessibility considerations matter when building custom interactive widgets with DOM events โ keyboard handling, ARIA, and focus?
What are the trickier edge cases of event delegation โ dynamically added/removed children, and the difference between target and currentTarget?
Why do frameworks like React wrap native browser events in their own synthetic event system instead of using raw DOM events directly?
If you were designing a tiny DOM abstraction library โ essentially a minimal jQuery โ what core tradeoffs would you need to think through?
Why shouldn't you use an arrow function as a method inside an object literal or a class, especially when you need 'this' to refer to the instance?
In a production app calling a third-party API with an unpredictable response shape, how would you combine optional chaining with nullish coalescing to write safe, defensive code?
In a large web app, how would you use dynamic import() to reduce the initial bundle size, and what does it return?
Can you walk through, in detail, exactly how the event loop processes the call stack, microtask queue, and macrotask queue together?
Can you implement a simplified version of Promise from scratch to show you understand how it works internally?
How would you implement debounce and throttle using setTimeout, and what's the real difference between them?
How would you handle a race condition where multiple async requests update the same piece of state, and only the latest response should count?
How do you cancel an in-flight fetch() request using AbortController?
How would you design retry logic with exponential backoff for a flaky API call?
How would you build a simple task queue that only allows a limited number of async operations to run concurrently (e.g., rate-limiting API calls)?
What kinds of subtle memory leaks can asynchronous code introduce in long-running applications, and how would you prevent them?
What is the relationship between async/await and generator functions combined with Promises โ what problem did async/await actually solve that generators didn't fully?
What is mixins in JavaScript OOP? How do you implement them?
What is composition over inheritance? When would you prefer it in JavaScript?
Explain the SOLID principles. How do they apply to JavaScript OOP?
What is the difference between classical inheritance and prototypal inheritance?
How do you design a plugin system using OOP principles in JavaScript?
What is the Singleton pattern in JavaScript? When should you use โ and avoid โ it?
What is a memory leak scenario in production and how would you debug it?
What is a closure-based memoization implementation and when does it make sense?
Predict the output of this event loop puzzle.
Implement a debounce function that supports both leading and trailing execution.
Implement a generic curry function that handles variadic arguments.
How would you implement memoization for functions with multiple arguments?
How would you use a Proxy to implement validation and access control?
What is the Reflect API and how does it complement Proxy?
What is the Reflect API used for independently of Proxy?
What is a functor in functional programming?
Design and implement a reactive state management system using Proxy.
What are async generators and how do they work with `for await...of`?
What is `generator.return()` and `generator.throw()` and when would you use them?
How would you implement a simple Observable using the functional programming approach?
You have a list of 10,000 DOM nodes to process. How would you avoid blocking the UI using the event loop?
What strategies do you use to handle errors gracefully at an application-wide level?
How do you debug a memory leak in a JavaScript application?
How would you implement optimistic UI updates in a JavaScript application?
How do you manage cookies securely for authentication in a modern JavaScript application?
How do you implement advanced form validation with real-time feedback and asynchronous checks?
What is the difference between code splitting, lazy loading, and tree shaking in JavaScript performance optimisation?
How do you implement a custom event system (pub/sub) for decoupled communication between modules?
How do you prevent and mitigate XSS attacks in a JavaScript application?
How do you architect a scalable state management system for a complex vanilla JavaScript application?
What is the Storage Event and how can you use it to sync data across multiple browser tabs?
How do you implement a robust, production-ready fetch wrapper with retries, timeouts, and cancellation?
Explain code splitting strategies for a large multi-page JavaScript application.
How do you implement input sanitisation and output encoding to prevent injection attacks beyond XSS?
What are the most common JavaScript interview questions for senior developers and how should you approach answering them?
Implement a deep clone function in JavaScript without using JSON.parse/JSON.stringify. Handle circular references, Dates, Maps, Sets, and Arrays.
Implement a Promise class from scratch that follows the Promises/A+ specification, supporting then(), catch(), finally(), and Promise.all().
Implement a simple Observable class (similar to RxJS) with subscribe(), map(), filter(), and take() operators.
Implement a virtual DOM diff algorithm. Given two virtual DOM trees (old and new), generate a list of patches (operations) needed to update the real DOM.
Implement an async job scheduler that processes jobs in priority order with support for cancellation and job dependencies.
Implement a concurrency-limited async map function: given an array of items, an async worker, and a concurrency limit, process all items and return results in original order, but stop and reject early if any item throws.
Implement a custom async iterator/generator that paginates through an API, yielding items one page at a time while abstracting away the pagination cursor logic.
Implement a WeakMap-based private data pattern to fully hide state from a class's public API (an alternative to private class fields, useful for pre-ES2022 environments).
Implement a function that performs structural sharing for immutable updates to a deeply nested object at an arbitrary path, without deep-cloning the entire tree.
Implement a custom async queue that processes tasks strictly in FIFO order (one at a time), where each task can itself enqueue more tasks, and expose a way to wait until the queue is fully drained.
Implement a function that computes the maximum flow value is not required โ instead implement a union-find (disjoint set) data structure with path compression and union by rank.
Implement a debounced async function wrapper where only the latest call's Promise resolves with a real result, and all earlier superseded calls resolve (not reject) with a special 'cancelled' marker rather than hanging forever.
Implement a simple reactive signal/computed system (similar to SolidJS/Vue signals): createSignal() for mutable state and createComputed() for derived values that automatically recompute and notify subscribers when dependencies change.
Implement a function that finds the shortest path between two nodes in a weighted graph using Dijkstra's algorithm.
Implement a function that solves the N-Queens problem: return all distinct board configurations where N queens can be placed on an N x N chessboard without attacking each other.
Implement a lock-free-style async mutex (mutual exclusion lock) that ensures only one async critical section runs at a time, with a lock() method returning a release function.
Implement a custom Array-like class that supports negative indexing (e.g. arr.at(-1)) and lazy evaluation of a map() chain (transformations only apply when the value is actually accessed), using Proxy.
Implement a function that serializes and deserializes a binary tree to/from a string, preserving the exact structure (including null children).
Implement an LRU cache using a doubly linked list combined with a hash map, achieving true O(1) get/put without relying on the Map's insertion-order behavior.
Implement a function that detects whether the V8 JIT-observable behavior of sparse vs dense arrays would matter: write a function demonstrating and explaining the performance difference between array holes and dense arrays.
Implement a custom Promise.race and Promise.any from scratch, correctly matching their edge-case semantics (empty arrays, all-rejected inputs).
Implement a function that finds all critical connections (bridges) in an undirected graph โ edges whose removal would disconnect the graph.
Implement a custom Promise.allSettled from scratch.
Implement a function that computes the k-th smallest element in a large stream of numbers using a max-heap of size k, without storing the entire stream.
Implement a function that builds a simple LRU-aware, TTL-expiring cache: entries expire after a configurable time-to-live in addition to normal LRU eviction on capacity overflow.
Implement a function that computes word ladder transformation length: the minimum number of single-character edits to transform a start word into an end word, where each intermediate word must exist in a given word list.
Implement a memory-efficient function that computes a running median from a stream of numbers using two heaps (a max-heap for the lower half, a min-heap for the upper half).
Implement a function that computes the maximum profit from stock trading allowing at most two transactions (buy-sell pairs, non-overlapping).
Implement a function that builds a simple in-memory reverse index (search engine style) over a collection of documents, supporting AND-queries across multiple terms.
Implement a circuit breaker pattern for async operations: track failures and 'open' the circuit (fail fast without calling the underlying function) after a failure threshold, then attempt a 'half-open' recovery after a cooldown period.
Implement a function that computes all combinations of k numbers from 1 to n (combinatorial generation, not permutations).
Implement a function that computes a hash of an object deterministically (stable regardless of key insertion order), suitable for cache keys or equality checks.
Implement a function that finds the maximum rectangle area in a histogram represented as an array of bar heights, using a monotonic stack.
Implement a function that simulates cooperative task scheduling using generators, allowing multiple 'coroutines' to interleave execution manually via a simple scheduler.
Implement a function that computes the maximum path sum in a binary tree (path can start and end at any node, doesn't have to pass through the root).
Implement an async task orchestrator that runs tasks based on a dependency graph (DAG), executing independent tasks in parallel and respecting dependency order, similar to a build system or task runner.
Implement a function that checks whether a given JavaScript object graph has a memory leak risk from an unintended closure retaining a large object โ demonstrate the pattern and a fix.
Implement a function that computes the number of ways to climb a staircase of n steps taking 1, 2, or 3 steps at a time, using memoized recursion.
Implement a function that partitions an array into k subsets with equal sum, if possible (backtracking approach).
Implement a function that computes matrix multiplication for two 2D arrays (matrices) with compatible dimensions.
Implement a function that finds the number of distinct subsequences of string s that equal string t (dynamic programming).
Implement a function that finds the minimum window substring of s that contains all characters of t (including duplicates), using the sliding window technique.
Implement a function that determines if a directed graph has a cycle, using three-color DFS (white/gray/black) marking.
Implement a function that computes the skyline of a set of buildings (each defined by [left, right, height]), producing the list of key points describing the city skyline silhouette.
Implement a function that solves the 'word search' problem: given a 2D board of letters and a word, determine if the word exists by tracing a path of adjacent cells (up/down/left/right), without reusing a cell.
Implement a function that finds all root-to-leaf paths in a binary tree that sum to a given target value.
Implement a function that performs run-length encoding and decoding of a string.
Implement a function that computes the diameter of a binary tree (the length in edges of the longest path between any two nodes, which may or may not pass through the root).
Implement an async function that races a Promise against a timeout, rejecting with a timeout error if the original Promise doesn't settle in time, while ensuring the timeout timer is always cleaned up to avoid leaking a pending setTimeout.
Implement a function that finds the celebrity in a party using the 'find the celebrity' problem: given an n x n matrix knows[i][j] (true if person i knows person j), find the celebrity โ someone everyone knows but who knows no one โ in better than O(n^2) comparisons where possible.