ExtraBrain Interview Questions

JavaScript Interview Questions for 2026: Event Loop, Closures and Async

Short answer

JavaScript interviews in 2026 focus on runtime behavior: predicting output from the event loop, closures in loops, how this is bound, and the differences between Promise.all, allSettled, any and race. Expect to implement a utility such as debounce or a concurrency-limited map, and to know recent additions like Set methods and iterator helpers. Say the output before you run the code.

JavaScript interview questions on the event loop, closures, this, promises and async utilities, with output puzzles and code tested in Node.js.

  • JavaScript
  • Coding Interviews
  • Frontend Interviews

Most JavaScript rounds include at least one “what does this print?” question, and most candidates who miss it know the concepts but have never traced them carefully. The other common format is “implement debounce” or “write a version of Promise.all with a concurrency limit,” followed by a change to the requirements.

This page is about runtime behavior and utilities. If you want the syntax side (let and const, destructuring, classes, modules), our ES6 interview questions cover it. Every snippet below runs as an ES module in a current Node.js release.

Diagram of the JavaScript event loop: run one task such as a script, timer callback or I/O event, let the call stack empty, drain the whole microtask queue including promise callbacks and await continuations, let the browser render if needed, then take the next task

Event loop questions

What does this print, and why?

console.log("A");
setTimeout(() => console.log("G"), 0);
Promise.resolve()
.then(() => console.log("D"))
.then(() => console.log("F"));
(async () => {
console.log("B");
await null;
console.log("E");
})();
console.log("C");
// A B C D E F G (one letter per line)

Walk through it. Synchronous code runs first, including the body of the async function up to its first await, so A, B and C print. Then the microtask queue drains completely. MDN’s microtask guide is explicit that promise callbacks are microtasks and that microtasks added while draining also run before the next task. D was queued first, the await continuation E second, and F is queued only when D’s callback finishes. The timer callback G is a task, so it runs last even with a delay of 0.

How is Node.js different?

Node adds process.nextTick and setImmediate. The Node.js event loop guide lists the phases (timers, pending callbacks, idle and prepare, poll, check, close callbacks) and says the next-tick queue is processed after the current operation, before the loop continues. It also says the order of setTimeout(fn, 0) and setImmediate is non-deterministic in the main module, but inside an I/O callback the immediate always runs first.

setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));

A detail that impresses interviewers: run this as a CommonJS file and nextTick prints before promise; run it as an ES module and promise prints first, because module code is evaluated asynchronously and the microtask queue drains before the next-tick queue gets a turn. Either way, timeout and immediate come after both and their order can vary.

Scope and binding questions

Why does the var loop print the same number three times?

const fns = [];
for (var i = 0; i < 3; i++) fns.push(() => i);
console.log(fns.map((f) => f())); // [ 3, 3, 3 ]
const fixed = [];
for (let j = 0; j < 3; j++) fixed.push(() => j);
console.log(fixed.map((f) => f())); // [ 0, 1, 2 ]

MDN’s closures guide explains it: var is function-scoped, so every closure shares one binding, which ends at 3. let creates a new binding for each iteration. Before let, the fix was a function factory or an immediately invoked function.

What is this inside a method you pass around?

const counter = {
count: 0,
increment() {
this.count += 1;
return this.count;
},
};
const inc = counter.increment;
try {
inc(); // called without an object: `this` is undefined in strict mode and modules
} catch (err) {
console.log(err.constructor.name); // TypeError
}
console.log(counter.increment()); // 1
console.log(inc.call(counter)); // 2
console.log(counter.increment.bind(counter)()); // 3
const timer = {
ticks: 0,
start() {
setTimeout(() => console.log(++this.ticks), 0); // the arrow keeps start()'s `this`
},
};
timer.start(); // 1

MDN’s reference for this gives the rules: this depends on how a function is called; a strict-mode function called without an object gets undefined; arrow functions keep the this of the enclosing scope and ignore call, apply and bind; and bind works only once. The classic bug is passing counter.increment as an event handler or callback and losing the object.

What are hoisting and the temporal dead zone?

console.log(typeof hoisted, hoisted()); // function hi
function hoisted() {
return "hi";
}
try {
console.log(notYet);
} catch (err) {
console.log(err.name); // ReferenceError
}
let notYet = 1;

Function declarations are hoisted with their bodies, so you can call them before the line that defines them. let, const and class declarations are hoisted too, but reading them before the declaration runs throws a ReferenceError; that window is the temporal dead zone. var is hoisted and initialized to undefined, which is why old code could read a variable “too early” without an error and get a confusing value instead.

How does prototypal inheritance relate to classes?

Every object has an internal link to a prototype, and property lookups walk that chain until they find the property or reach null. A class is mostly syntax over this model: methods live on ClassName.prototype, and extends links one prototype to another. The differences worth naming are that class bodies always run in strict mode, classes aren’t hoisted the way function declarations are, and private fields (#count) are enforced by the language rather than by naming convention.

How do you deep-copy an object?

const original = { when: new Date(0), tags: new Map(Object.entries({ lang: "js" })), note: undefined };
original.self = original;
const viaJson = JSON.parse(JSON.stringify({ ...original, self: null }));
console.log(typeof viaJson.when, viaJson.tags, "note" in viaJson); // string {} false
const copy = structuredClone(original);
console.log(copy.when instanceof Date, copy.tags.get("lang"), copy.self === copy); // true js true
try {
structuredClone({ fn() {} });
} catch (err) {
console.log(err.name); // DataCloneError
}

The JSON round trip turns dates into strings, empties the Map, drops undefined and throws on cycles, which is why the cycle had to be removed first. structuredClone keeps dates, maps and circular references, and throws a DataCloneError for values it can’t serialize, such as functions.

Implementation questions

Implement debounce.

function debounce(fn, waitMs) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), waitMs);
};
}
const search = debounce((query) => console.log("search:", query), 50);
search("r");
search("re");
search("rea");
setTimeout(() => search("react"), 100);
// search: rea (about 50 ms after the last call)
// search: react (about 150 ms after the start)

Explain why the wrapper is a regular function (to forward this to fn) and offer the follow-ups before you’re asked: a leading-edge option, a cancel method, and how throttle differs, since throttle runs at most once per interval instead of waiting for quiet.

Run async tasks with a concurrency limit, keeping result order.

async function mapLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const i = next++; // safe: JavaScript runs this synchronously between awaits
results[i] = await fn(items[i], i);
}
}
const workers = Array.from({ length: Math.min(limit, items.length) }, worker);
await Promise.all(workers);
return results;
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let active = 0;
let peak = 0;
const doubled = await mapLimit([30, 10, 20, 5, 15], 2, async (ms) => {
active++;
peak = Math.max(peak, active);
await sleep(ms);
active--;
return ms * 2;
});
console.log(doubled, "peak:", peak); // [ 60, 20, 40, 10, 30 ] peak: 2

Point out the failure behavior: if one call rejects, Promise.all rejects, but the other workers keep running. If the interviewer wants every result, collect errors per item or build on Promise.allSettled.

When do you use each Promise combinator?

MDN’s Promise reference summarizes them:

MethodFulfills whenRejects when
Promise.allAll fulfillAny rejects
Promise.allSettledAll settleNever
Promise.anyAny fulfillsAll reject
Promise.raceFirst one settles by fulfillingFirst one settles by rejecting

A typical use for race is a timeout around a fetch, though AbortSignal.timeout now cancels the underlying request as well.

How do you cancel a request that is no longer needed?

Pass an AbortSignal to fetch. Create an AbortController, give its signal to the request, and call abort() when the user types a new search query or leaves the page; the pending promise rejects with an AbortError that you catch and ignore. AbortSignal.timeout(ms) creates a signal that aborts on its own, and AbortSignal.any([a, b]) combines a user-cancel signal with a timeout. Mention why it matters in a typeahead: without cancellation, a slow response for “re” can arrive after the fast response for “react” and overwrite the newer results.

Recent language questions

What has the language added recently?

The TC39 finished proposals list shows ES2025 adding Set methods, iterator helpers, Promise.try, import attributes and JSON modules, among others. ES2026 adds Array.fromAsync, Error.isError, Math.sumPrecise, RegExp.escape and base64 helpers on Uint8Array. Temporal and explicit resource management (using) are listed for 2027. A short demo is enough:

const frontend = new Set(["js", "ts", "react"]);
const backend = new Set(["ts", "go", "sql"]);
console.log(frontend.intersection(backend)); // Set(1) { 'ts' }
console.log(frontend.union(backend).size); // 5
const firstTwoEvens = [1, 2, 3, 4, 5, 6, 7, 8]
.values()
.filter((n) => n % 2 === 0)
.map((n) => n * 10)
.take(2)
.toArray();
console.log(firstTwoEvens); // [ 20, 40 ]
const userInput = "1+1=2";
console.log(new RegExp(userInput).test("1+1=2")); // false: + is a quantifier
console.log(new RegExp(RegExp.escape(userInput)).test("1+1=2")); // true (ES2026)

Iterator helpers are lazy: take(2) stops the pipeline after two matches, so the remaining elements are never mapped. Support still varies by runtime. On the Node.js 26 release used to test this page, RegExp.escape and Error.isError work, Math.sumPrecise isn’t available yet, and Temporal already is. Check support before using the newest methods in client code.

Practice tracing out loud

Output questions reward a calm, step-by-step trace: “synchronous first, then the microtask queue, then the next task.” Practice saying that sequence while you work through new snippets. If you record practice sessions with ExtraBrain, the transcript shows where you guessed instead of traced. The frontend developer mock interview page has more prompts, and our TypeScript interview questions build on this page. Use ExtraBrain in a live interview only where the employer allows AI assistance.

FAQ

Do I need to know the browser event loop and the Node one?

For frontend roles, the browser model (tasks, microtasks, rendering) matters most. For full-stack or backend roles, add Node’s phases, nextTick and setImmediate.

Is == ever acceptable?

Many style guides allow x == null as a shorthand for null or undefined. Otherwise use ===, and be ready to explain one coercion example.

What causes memory leaks in JavaScript apps?

Listeners and timers that are never removed, caches without limits, and closures that keep large objects alive. An AbortController signal passed to addEventListener makes listener cleanup straightforward.

Sources (checked November 21, 2026)