JavaScript Interview Questions and Answers

35 JavaScript interview questions with answers and code: types and coercion, scope and closures, this, prototypes, the event loop, promises, async/await, modules and coding exercises.

Updated November 20, 2026 35 questions 7 min read

Key takeaways

  • JavaScript interviews revolve around closures, this, prototypes and the event loop.
  • Expect output-prediction questions: what does this code log, and in what order?
  • Mid-level candidates should explain promises vs async/await, microtasks vs macrotasks, and error handling.
  • Classic coding tasks: debounce, throttle, deep clone, Promise.all, flattening arrays.
Contents

JavaScript interviews test whether you understand how the language behaves: closures, this, prototypes and the event loop, plus small utilities you can write from scratch. Below are 35 questions grouped by topic and level, with answers and code.

What JavaScript interviews cover

Typical topic mix in a JavaScript interview

Editorial estimate for a frontend or full-stack role.

45–60minutes
  • Async and the event loop25%
  • Scope, closures and this25%
  • Coding utilities25%
  • Types and coercion10%
  • DOM and browser10%
  • Modules and tooling5%

The event loop in one picture

What runs when
  1. Synchronous codeEverything on the call stack runs to completion first.
  2. All microtasksPromise callbacks (then, await continuations) and queueMicrotask, until the queue is empty.
  3. One macrotaskA timer, I/O callback or UI event.
  4. RepeatMicrotasks again, then the next macrotask; rendering happens between tasks in the browser.

Continue with React interview questions, Node.js questions or the full frontend interview list.

Types and values

1What are the primitive types in JavaScript?

Junior

string, number, bigint, boolean, undefined, symbol and null. Everything else is an object, including arrays and functions. Primitives are immutable and compared by value; objects are compared by reference.

2What is the difference between == and ===?

Junior

=== compares without type conversion. == converts types first, which leads to surprises like 0 == "" being true. Use === by default; x == null is a common accepted shortcut for checking both null and undefined.

3null vs undefined?

Junior

undefined means a value was never assigned (missing variable value, missing property, function without return). null is an intentional “no value”. typeof null returns "object", a historical quirk.

4Which values are falsy?

Junior

false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including "0", [] and {}.

5Why does 0.1 + 0.2 !== 0.3?

Mid

Numbers are 64-bit floating point, and 0.1 and 0.2 can’t be represented exactly in binary. Compare with a tolerance (Math.abs(a - b) < Number.EPSILON) or work in integer units such as cents for money.

6How do you deep clone an object?

Mid

structuredClone(obj) handles nested objects, arrays, dates, maps and sets. JSON.parse(JSON.stringify(obj)) loses functions, dates and undefined. The spread operator {...obj} is only a shallow copy.

Scope and closures

7var vs let vs const?

Junior

var is function-scoped and hoisted with the value undefined. let and const are block-scoped and exist in a “temporal dead zone” before their declaration. const prevents reassignment, not mutation of the object it holds.

8What is hoisting?

Junior

Declarations are processed before code runs. Function declarations are fully hoisted (you can call them before they appear); var variables are hoisted as undefined; let, const and classes are hoisted but can’t be used before the declaration line.

9What is a closure?

Junior

A function that keeps access to variables from the scope where it was created:

function makeCounter() {
  let count = 0;
  return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2

Closures power private state, callbacks and many patterns like memoization.

10What does this code log, and why?

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

It logs 3, 3, 3, because var creates one shared variable and the callbacks run after the loop. With let, each iteration gets its own binding and it logs 0, 1, 2.

Get JavaScript answer points in real time during your interview

Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.

this, prototypes and classes

11How is this determined?

Mid

By how a function is called: as a method (obj.f() → obj), as a plain function (undefined in strict mode), with new (the new object), or explicitly with call, apply and bind. Arrow functions don’t have their own this; they use the surrounding one.

12call vs apply vs bind?

Mid

call(thisArg, a, b) and apply(thisArg, [a, b]) invoke the function immediately with a given this. bind(thisArg) returns a new function with this fixed, to call later.

13How does prototypal inheritance work?

Mid

Every object has an internal link to a prototype. When a property isn’t found on the object, JavaScript looks it up along the prototype chain. class syntax is a cleaner way to set up the same prototype chain.

14Arrow functions vs regular functions?

Junior

Arrow functions have no own this, arguments or prototype, and can’t be used with new. They are ideal for callbacks; regular functions or methods are better when you need dynamic this.

Asynchronous JavaScript

15Explain the event loop.

Mid

JavaScript runs on one thread with a call stack. Async work (timers, network) is handled by the environment, and callbacks are queued. When the stack is empty, the event loop first runs all microtasks (promise callbacks, queueMicrotask), then one macrotask (timer, I/O, UI event), then microtasks again, and so on.

16What is the output order?

Mid
console.log(1);
setTimeout(() => console.log(2));
Promise.resolve().then(() => console.log(3));
console.log(4);

1, 4, 3, 2. Synchronous code runs first, then microtasks (the promise), then the timer macrotask.

17What is a Promise?

Junior

An object representing a future result: pending, then fulfilled or rejected. You chain .then() and .catch(), or use await. Promises replaced deeply nested callbacks and make error handling composable.

18Promise.all vs allSettled vs race vs any?

Mid

all resolves when all succeed and rejects on the first failure. allSettled waits for all and reports each result. race settles with the first promise to settle. any resolves with the first success and rejects only if all fail.

19How do you handle errors with async/await?

Mid

Wrap awaits in try/catch, or attach .catch() to the returned promise. Avoid running independent requests sequentially; start them together:

const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);

20How do you cancel a fetch request?

Senior

With an AbortController: pass controller.signal to fetch and call controller.abort(). The promise rejects with an AbortError, which you usually ignore. This prevents race conditions where an old response overwrites a newer one.

Browser and modules

21What is event delegation?

Junior

Attaching one listener to a parent instead of many to children, and using event.target to find which child was clicked. It works because events bubble up the DOM, and it handles elements added later.

22Event bubbling vs capturing?

Mid

Events travel down from the window to the target (capturing), then back up (bubbling). Listeners run in the bubbling phase by default; pass { capture: true } to listen during capturing. stopPropagation() stops further travel.

23ES modules vs CommonJS?

Mid

ES modules use import/export, are statically analyzable (enabling tree shaking) and load asynchronously. CommonJS uses require/module.exports and loads synchronously; it is the legacy Node.js format. Modern code uses ES modules.

24localStorage vs sessionStorage vs cookies?

Junior

localStorage persists until cleared; sessionStorage lasts for the tab session; both hold a few megabytes and are only accessible from JavaScript. Cookies are small, sent to the server with requests, and can be HttpOnly and Secure, which makes them the right place for session tokens.

25How do memory leaks happen in JavaScript apps?

Senior

Through references that keep objects alive: forgotten timers and event listeners, growing caches, detached DOM nodes still referenced in code, and closures holding large objects. Find them with heap snapshots in DevTools.

Modern syntax

26What do destructuring, spread and rest do?

Junior

Destructuring extracts values: const { id, name } = user. Spread expands: [...a, ...b], { ...defaults, ...options }. Rest collects the remainder: function f(first, ...others).

27What are optional chaining and nullish coalescing?

Junior

user?.address?.city returns undefined instead of throwing if something in the chain is missing. value ?? 'default' falls back only for null or undefined, unlike ||, which also replaces 0 and "".

28map, filter and reduce: when do you use each?

Mid

map transforms each item, filter keeps matching items, reduce combines items into one value (sum, grouping). They return new arrays and don’t mutate the original, which keeps code predictable.

29Map vs plain object, Set vs array?

Mid

Map allows keys of any type, keeps insertion order and has a size; it is better for frequent additions and removals. Set stores unique values with fast has checks, much faster than array.includes for large collections.

Coding exercises

30Implement debounce.

Mid
function debounce(fn, delay) {
  let id;
  return function (...args) {
    clearTimeout(id);
    id = setTimeout(() => fn.apply(this, args), delay);
  };
}

The function runs only after calls stop for delay milliseconds. Typical use: search input.

31Implement throttle.

Mid
function throttle(fn, interval) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last >= interval) {
      last = now;
      fn.apply(this, args);
    }
  };
}

Runs at most once per interval. Typical use: scroll and resize handlers.

32Implement Promise.all.

Mid
function all(promises) {
  return new Promise((resolve, reject) => {
    const results = [];
    let done = 0;
    if (promises.length === 0) return resolve(results);
    promises.forEach((p, i) => {
      Promise.resolve(p).then(value => {
        results[i] = value;
        if (++done === promises.length) resolve(results);
      }, reject);
    });
  });
}

33Flatten a nested array.

Junior

Built in: arr.flat(Infinity). Recursive version:

const flatten = arr => arr.reduce(
  (acc, x) => acc.concat(Array.isArray(x) ? flatten(x) : x), []);

34Group an array of objects by a key.

Mid
const byCategory = Object.groupBy(products, p => p.category);
// older environments:
const grouped = products.reduce((acc, p) => {
  (acc[p.category] ??= []).push(p);
  return acc;
}, {});

35Implement a simple event emitter.

Senior
class Emitter {
  #handlers = new Map();
  on(event, fn) {
    if (!this.#handlers.has(event)) this.#handlers.set(event, new Set());
    this.#handlers.get(event).add(fn);
    return () => this.#handlers.get(event).delete(fn);
  }
  emit(event, ...args) {
    this.#handlers.get(event)?.forEach(fn => fn(...args));
  }
}

Returning an unsubscribe function helps avoid memory leaks.

How to prepare

  1. Predict the outputPractice snippets with closures, this, hoisting and promise ordering; explain each line.
  2. Implement utilities from scratchDebounce, throttle, deep clone, Promise.all, memoize and an event emitter.
  3. Know the event loop coldBe able to draw the call stack, microtask queue and macrotask queue.
  4. Use modern syntax naturallyOptional chaining, nullish coalescing, destructuring, Map and Set.
  5. Connect to your frameworkExpect follow-ups on how this applies in React, Vue or Node.js.

Get answer points in real time during your interview

Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.

Related interview questions