Contents

JavaScript Interview Questions (Closures, Event Loop, Async, and More) | OfferBull

JavaScript Interview Questions (Closures, Event Loop, Async, and More)

They write for (var i = 0; i < 3; i++) on the board, drop a setTimeout inside it that logs i, and wait.

You know the punchline is 3, 3, 3. Saying only the punchline is how people fail this. They want the captured binding, why let changes the result, and whether you can say it without turning the room into a lecture.

That’s what javascript interview questions feel like on a frontend or full-stack loop. Scope, closures, this, the event loop, promises, prototypes. Language fundamentals, not a React quiz. Hooks and component state already have their own post: React interview questions. For the rest of a frontend loop, use how to prepare for frontend engineering interviews. If the role leans Node, go to Node.js interview questions after you can talk through this one.

Samples below are made up. Say them out loud. Reading silently will not catch the “so basically” that shows up under a clock.

Scope, closures, and this

var is function-scoped. It is hoisted and starts as undefined, so a read before the line that assigns it does not throw, which surprises people who learned let first. let and const are block-scoped and live in the temporal dead zone until the declaration runs. Read them early and you get a ReferenceError, not undefined.

const is a binding you cannot reassign. It is not a frozen object. const user = { name: 'Ada' }; user.name = 'Grace' is legal. user = {} is not. If you need a frozen object, say Object.freeze, and even then know it is shallow.

A closure is a function that still sees the variables from the scope where it was created, after that scope has returned. The part interviewers care about: it captures the binding, not a snapshot of the value at creation time. That is the loop-plus-var trap. One i, mutated on every iteration, shared by every callback. let gives each iteration its own binding, so the callbacks see 0, 1, 2.

Useful closures in real code look boring: a click handler that remembers an id, a small module with private state, a debounce wrapper. If your only example is the var loop, it sounds like a quiz, not a codebase.

Spoken: “A closure keeps the bindings from the scope where the function was created. With var in a loop, every callback shares one i, so after the loop it is 3. let makes a binding per iteration. I use closures for handlers and small private state. I do not treat const as a frozen object.”

Then they move to this, which is a binding rule, not a personality trait of the function.

  • Default: a bare call, fn(), gets undefined in strict mode. ES modules are strict, so treat most snippets that way. In sloppy mode it is the global object, which is why old answers mention window.
  • Implicit: obj.method() binds this to obj. Pull the function off (const fn = obj.method; fn()) and the binding is gone.
  • Explicit: call, apply, and bind set this on purpose. bind returns a new function.
  • Arrow functions do not have their own this. They close over this from the enclosing scope. bind does not rebind an arrow. You cannot new one.
  • new: this is the newly created instance, unless the constructor explicitly returns another object.

Q: You have button.onClick = user.greet, and greet uses this.name. It prints undefined. Why?

A: “The method was extracted. The event system calls it as a bare function, so this is not user. I’d bind it, wrap it in an arrow that calls user.greet(), or make greet an arrow on the object only if the lexical this is actually what I want, which it usually isn’t at the top level of a module.”

/images/posts/javascript-interview-questions/closures-scope-board.jpg A closure sketch is just nested scopes. Keep the words in your mouth, not all over the board.

Event loop, promises, and async/await

JavaScript in the browser runs on a single call stack. That is the part people remember. The rest is the host: timers, DOM events, network, and the queues that feed work back onto that stack.

A quick model is enough. The call stack runs your code. Host APIs hold the timer or the fetch. When a timer fires, its callback is queued as a task (a macrotask: setTimeout, setInterval, many I/O and UI events). When a promise settles, its .then, .catch, and .finally reactions are queued as microtasks, along with queueMicrotask.

After the current stack clears, the engine drains the microtask queue completely, then takes one task from the task queue, then drains microtasks again. That is why Promise.resolve().then(...) can run before setTimeout(..., 0). The timeout of 0 is not “run now.” It is “run on a later task.” The promise reaction is a microtask, so it wins that race.

async/await is promises with different syntax. An async function always returns a promise. return 1 becomes a fulfillment with 1. A thrown error becomes a rejection. await pauses that function, yields back to the caller, and schedules the remainder as promise work when the awaited value settles. try / catch around await catches a rejection. If you neither await nor attach .catch, you can get an unhandled rejection, which is a real bug, not a style note.

Spoken: “Call stack first. Microtasks, including promise reactions, run after the stack clears and before the next timer callback. async functions return promises. I await inside try / catch, or I chain .catch. I don’t pretend setTimeout(fn, 0) is sooner than a thenable that already resolved.”

Q: You await two independent requests in sequence, and the interviewer asks why it is slow.

A: “If they don’t depend on each other, I’d start both, then await Promise.all. Sequencing await is fine when the second call needs the first result. I’d say that trade out loud instead of treating every await as automatically concurrent.”

A Node interview will take this same idea into libuv, the threadpool, and what actually blocks a server process. That is the Node.js interview questions post. Here, get the stack, the microtasks, and the timeout-of-zero question clean.

/images/posts/javascript-interview-questions/event-loop.svg Drain microtasks after the stack, before the next timer. That is the Promise-versus-setTimeout(0) question.

Prototypes and classes

Every object has an internal [[Prototype]]. You read it with Object.getPrototypeOf. Property lookup walks that chain until it finds an own property or hits null. Object.create(proto) makes an object whose prototype is proto, which is still the clearest way to show you understand the model.

class, extends, and super are the syntax you should use in new code. They sit on the same prototype model. I would not say “it’s just sugar” and sit down. A few edges are not identical to a handmade constructor.

Class constructors have to be called with new. Class bodies run in strict mode. Methods on the prototype are non-enumerable. Class declarations are in the temporal dead zone, like let. In a subclass constructor you must call super() before you touch this. super.method() looks up the method on the parent, and this stays the current instance.

Own versus inherited comes up in unexpected ways. Object.hasOwn(obj, 'x') (or Object.prototype.hasOwnProperty.call in older code) asks whether x lives on obj. The in operator walks the chain, so 'toString' in obj is usually true even if you never set it.

Spoken: “I describe lookup as a walk up [[Prototype]]. class is the syntax I write, but I can still draw Object.create. The differences I mention if they push: new is required, super() before this in a subclass, TDZ, methods are not enumerable. I don’t claim a hand-rolled prototype setup is identical in every edge case.”

Output-prediction questions

These are short. Predict the output out loud, then say why, then mention the production version of the bug if there is one. Don’t narrate every token.

1. The loop everyone expects.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

Output: 3, 3, 3. One function-scoped i. The timeouts run after the loop. Change var to let and you get 0, 1, 2. A closure over a unique value also works: an inner function with its own parameter, or a bind. In real code I’d just use let or forEach.

2. this on a method, then pulled off, then an arrow.

const user = {
  name: 'Ada',
  greet() {
    console.log(this.name);
  },
  arrow: () => console.log(this.name),
};

user.greet();
const fn = user.greet;
fn();
user.arrow();

In a module (strict): Ada, then a TypeError when you read this.name on undefined. The arrow does not bind to user; it uses the enclosing this, which at module top level is undefined. I assume strict unless they say otherwise, and I say that assumption.

3. Promise versus a timeout of zero.

console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');

Output: A, D, C, B. Stack first (A, D), then the microtask (C), then the timer task (B).

4. What an async function actually returns.

async function go() {
  return 1;
}

console.log(go());

You do not get 1. You get a promise that fulfills with 1. If they follow with throw inside go and no try, the call itself does not throw. You get a rejected promise. It becomes a thrown error at the call site only if someone awaits it, or if they failed to handle the rejection.

5. An arrow inside a method, plus a regular function in a timeout.

const obj = {
  n: 1,
  later() {
    setTimeout(() => console.log('arrow', this.n), 0);
    setTimeout(function () {
      console.log('fn', this.n);
    }, 0);
  },
};

obj.later();

The arrow prints arrow 1, because it closed over this from later(). The regular function loses this (strict: this.n throws; sloppy: you get undefined from the global object). The production version is a timer or event callback where this vanished. Fix with an arrow, const self = this, or bind.

If you want practice saying the reasoning while someone interrupts you, see how to communicate your thought process during technical interviews. The snippets are the content. The talking is the test.

/images/posts/javascript-interview-questions/output-prediction-practice.jpg Output-prediction is a spoken drill. Cover the snippet, say the output, then uncover and check.

What else shows up on a frontend loop

A JavaScript screen is often the first half of a frontend interview, not the whole day.

If they start asking about hooks, stale closures in useEffect, or why a list re-renders, switch posts. That is React interview questions, not something to cram into a prototype answer. The frontend preparation guide covers the wider loop: CSS, performance, accessibility, and how the rounds fit together. Full-stack jobs mix this material with API and Node questions; see how to prepare for full-stack engineering interviews.

There is usually a coding round too. Don’t turn this article into a LeetCode list. Use the same patterns you would in any language, then write them in clear JavaScript. Top coding interview patterns and Blind 75 vs NeetCode 150 will get you further than another closure blog. When they ask for complexity, talk it the way the Big O post suggests: name the tight loop and the extra arrays. Some companies start with a CodeSignal General Coding Assessment; confirm the format with the recruiter. If JavaScript is only the frontend slice of a Python or Java shop, keep Python or Java for experienced developers in the same study week, and don’t mix the runtimes in one answer.

Night-before drill

I’d run these out loud, timer on, no notes after the first pass:

  • var vs let / const, including the temporal dead zone and what const does not freeze
  • Closures capture bindings, plus the loop trap and one real handler example
  • this for a method, an extracted function, an arrow, and new
  • Event loop: stack, microtasks, setTimeout(0), why the promise wins
  • async returns a promise; try / catch vs .catch
  • One prototype vs class difference that is not “sugar”
  • Two output-prediction snippets, covered, said, then checked
  • One “what I’d do in production” version of a lost-this or unhandled-rejection bug

If a pass is sloppy, repeat those two items, not the whole list.

Practicing with OfferBull

Flashcards will not train the pause before you say “event loop.”

OfferBull is an AI mock interview app for iOS and Android. A voice interviewer asks questions aloud. You answer by speaking. Paste a JavaScript or frontend job description, or upload a resume, for tailored questions. Follow-ups based on what you said and what’s on the resume. While you practice, you get answer suggestions and STAR structures. English and Chinese. It’s for rehearsal before the interview, not a helper during one.

Start an AI mock interview

FAQ

Do I need to memorize every event-loop phase? No. Stack, microtasks versus tasks, and why a resolved promise beats setTimeout(0) is enough. Save libuv and the threadpool for a Node.js round.

Should I still learn var? Yes, enough to explain it and to read older code. Write let and const in new answers unless they hand you existing var and ask what it does.

Are classes required? Most teams write class now. You should be able to use extends and super correctly, and still explain lookup on [[Prototype]] if they go back to the model.

How many output-prediction puzzles should I grind? A handful of patterns, not a hundred variants. Loop closures, this, promise versus timeout, and what async returns cover most rooms. If a snippet is cute but rare, skip it.

Will they ask me to write a promise from scratch? Sometimes. A small thenable that settles once is enough. Don’t start a full Promises/A+ library unless they ask you to keep going.


Practice This Out Loud

Tonight, cover one snippet at a time: the var loop, a lost this, and the A D C B promise-versus-timeout line. Say the output first, then the reason, in under a minute each. Then explain closures and this with no code in front of you. Record it. On playback, listen for filler and for answers that stop at the punchline. Then run the same questions in a voice mock that pushes back, and close the app before any real interview. → Practice Now


Take Control of Your Career Path: