JavaScript interview questions

20 JavaScript interview questions and answers

Core JavaScript questions for frontend, backend and full-stack interviews: closures, the event loop, promises and async code, this, prototypes, copying, modules and memory. Every question has a 30-second answer, a deeper explanation, code and the follow-ups to expect.

20 questions with a 30-second answer, a deeper explanation and the follow-ups interviewers usually ask.

How to use these questions

JavaScript interviews are less about syntax trivia than about whether you understand how the language actually behaves. Most questions fall into four groups: scope and functions (closures, hoisting, this, arrow functions), asynchronous behaviour (the event loop, promises, async and await), objects and data (prototypes, copying, equality, null versus undefined) and the platform (modules, events and memory).

The questions that separate candidates are usually the follow-ups. Everyone can say a closure remembers its surrounding scope; fewer can predict the output of a loop that creates callbacks with var, or explain why a promise callback runs before a setTimeout of zero. Practise predicting output, not just reciting definitions.

Read the question, answer aloud, then compare with the 30-second answer. Questions marked Often asked deserve the most rehearsal. If you hesitate on one, run the code in a console and change it until the result stops surprising you.

JavaScript

Closures, the event loop, async and this

Q1EasyFresherOften asked

What is a closure? Give a practical use.

30-second answer: A closure is a function that remembers the variables from where it was created, even after the outer function has finished. It gives you private state and function factories.

A closure is a function bundled with the variables of the scope where it was defined. The function keeps access to those variables even after the outer function has returned.

Typical uses: private state, function factories, memoization and callbacks that remember configuration.

JavaScript
function counter() {
  let n = 0;
  return () => ++n;
}
const next = counter();
next(); // 1
next(); // 2
Python
def counter():
    n = 0
    def inc():
        nonlocal n
        n += 1
        return n
    return inc

next_id = counter()
next_id()  # 1
next_id()  # 2
TypeScript
function counter(): () => number {
  let n = 0;
  return () => ++n;
}
const next = counter();
next(); // 1

Follow-up questions interviewers ask next

  • What goes wrong with var in a loop and a closure?
  • Can closures cause memory leaks?
  • Where do closures bite in React hooks?
Q2HardSeniorOften asked

Explain the event loop, microtasks and macrotasks.

30-second answer: JavaScript has one thread. After each task it drains all microtasks, like promise callbacks, before taking the next macrotask like setTimeout. That is why a resolved promise always beats setTimeout zero.

JavaScript runs on one thread. The call stack executes synchronous code; when it is empty the event loop takes the next task.

After every task the engine drains the whole microtask queue (promise callbacks, queueMicrotask) before taking the next macrotask (setTimeout, I/O, UI events). That is why a resolved promise always runs before a setTimeout(…, 0).

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

Follow-up questions interviewers ask next

  • Where do requestAnimationFrame callbacks run?
  • How does the Node.js event loop differ?
Q3EasyFresher

== vs === - what is the difference?

30-second answer: Triple equals checks value and type. Double equals converts types first and gives surprising results. Use triple equals, except x == null to catch both null and undefined.

=== compares value and type with no conversion. == converts operands to a common type first, which produces surprising results such as 0 == "" and null == undefined.

Use === by default. The one common exception is x == null, which checks for both null and undefined.

Follow-up questions interviewers ask next

  • What does Object.is do differently?
  • Why is NaN not equal to itself?
Q4EasyFresher

var, let and const - scope and hoisting?

30-second answer: var is function-scoped and starts as undefined. let and const are block-scoped and cannot be used before their declaration. const stops reassignment, not mutation.

var is function-scoped and hoisted with the value undefined. let and const are block-scoped and hoisted but unusable until their declaration runs (the temporal dead zone).

const prevents reassignment of the binding, not mutation of the object it points to.

console.log(a); // undefined
var a = 1;
console.log(b); // ReferenceError
let b = 2;

Follow-up questions interviewers ask next

  • What is the temporal dead zone?
  • Can you push to a const array?
Q5Medium2–5 years

How is this determined in JavaScript?

30-second answer: this depends on how a function is called: a method call gives the object, a plain call gives undefined in strict mode, new gives the new instance. Arrow functions take this from the surrounding scope.

this is set by how a function is called, not where it is defined: method call → the object before the dot; plain call → undefined in strict mode; new → the new instance; call/apply/bind → the value you pass.

Arrow functions have no this of their own and use the one from the enclosing scope.

Follow-up questions interviewers ask next

  • What do call, apply and bind do?
  • Why do class methods lose this when passed as callbacks?
Q6Medium2–5 years

Debounce vs throttle - when do you use each?

30-second answer: Debounce waits until the user stops, then runs once - good for search boxes. Throttle runs at a fixed maximum rate - good for scroll handlers.

Debounce waits until calls stop for N ms, then runs once - good for search-as-you-type and resize-end. Throttle runs at most once every N ms while calls continue - good for scroll and mousemove handlers.

JavaScript
function debounce(fn, ms) {
  let t;
  return (...args) => {
    clearTimeout(t);
    t = setTimeout(() => fn(...args), ms);
  };
}
TypeScript
function debounce<A extends unknown[]>(
  fn: (...args: A) => void,
  ms: number
) {
  let t: ReturnType<typeof setTimeout>;
  return (...args: A) => {
    clearTimeout(t);
    t = setTimeout(() => fn(...args), ms);
  };
}

Follow-up questions interviewers ask next

  • How would you add a leading-edge option?
  • Write a throttle function.
Q7Medium2–5 years

Promise.all vs Promise.allSettled vs Promise.race?

30-second answer: all fails fast if any promise fails. allSettled waits for every promise and reports each outcome. race returns whichever settles first.

Promise.all resolves with every result or rejects on the first failure. Promise.allSettled always resolves with each outcome as {status, value|reason}. Promise.race settles with whichever promise settles first, success or failure.

Use allSettled when partial failure is acceptable, e.g. loading independent dashboard widgets.

Follow-up questions interviewers ask next

  • What does Promise.any do?
  • How do you add a timeout to fetch using race?
Q8Medium2–5 yearsOften asked

Explain prototypal inheritance and the prototype chain.

30-second answer: Objects inherit through a prototype chain: a missing property is looked up on the object's prototype, then that object's prototype, until null. Classes are syntax over the same mechanism.

Every object has an internal link to another object, its prototype. When you read a property that is not on the object itself, JavaScript follows that link up the prototype chain until it finds the property or reaches null.

Functions called with new set the prototype of the new object to Constructor.prototype, and class syntax is a cleaner way to write the same mechanism. Object.create(proto) makes an object with a chosen prototype directly. Methods defined on the prototype are shared by every instance, which saves memory compared with copying them onto each object.

function Dog(name) {
  this.name = name;
}
Dog.prototype.speak = function () {
  return this.name + ' barks';
};

const rex = new Dog('Rex');
rex.speak(); // found on Dog.prototype, shared by all dogs
Object.getPrototypeOf(rex) === Dog.prototype; // true

Follow-up questions interviewers ask next

  • What is the difference between __proto__ and prototype?
  • How do ES6 classes relate to prototypes?
Q9Medium2–5 years

What is the difference between call, apply and bind?

30-second answer: call and apply run the function now with a chosen this, passing arguments separately or as an array. bind returns a new function with this fixed for later.

All three set this for a function. call(thisArg, a, b) invokes it immediately with arguments listed one by one. apply(thisArg, [a, b]) invokes it immediately with an array of arguments. bind(thisArg, a) does not invoke it; it returns a new function with this (and optionally the leading arguments) fixed.

Use bind for callbacks that need a fixed this, such as passing a class method as an event handler. Arrow functions have no this of their own, so call, apply and bind cannot change it.

function greet(greeting, punctuation) {
  return greeting + ', ' + this.name + punctuation;
}
const user = { name: 'Asha' };

greet.call(user, 'Hello', '!');      // Hello, Asha!
greet.apply(user, ['Hello', '!']);   // Hello, Asha!
const hi = greet.bind(user, 'Hi');   // function with this and greeting fixed
hi('?');                             // Hi, Asha?

Follow-up questions interviewers ask next

  • Why does passing obj.method as a callback lose its this?
  • Can you rebind an arrow function?
Q10EasyFresher

How do arrow functions differ from regular functions?

30-second answer: Arrow functions take this and arguments from their surrounding scope and cannot be constructors. Use them for callbacks; use regular functions for methods and constructors.

Arrow functions have a shorter syntax and do not have their own this, arguments or super; they use the ones from the surrounding scope. They also cannot be used as constructors with new.

That makes them ideal for callbacks inside methods, where you want this to stay the same. Use a regular function when you need your own this, such as an object method or a constructor.

const timer = {
  seconds: 0,
  start() {
    setInterval(() => {
      this.seconds += 1; // arrow keeps this = timer
    }, 1000);
  },
};

Follow-up questions interviewers ask next

  • Why is an arrow function a poor choice for an object method?
  • How would you return an object literal from a one-line arrow function?
Q11EasyFresherOften asked

What are promises, and how do async and await relate to them?

30-second answer: A promise is a placeholder for a future value that ends fulfilled or rejected. async/await is syntax on top of promises, and independent awaits should be started together with Promise.all.

A promise represents a value that will be available later and is in one of three states: pending, fulfilled or rejected. You attach handlers with then, catch and finally. An async function always returns a promise, and await pauses the function until a promise settles, so asynchronous code reads like synchronous code.

The code after an await runs as a microtask once the promise settles. Awaiting several independent promises one after another runs them in sequence; start them together and await Promise.all to run them concurrently.

// Sequential: about 2 seconds if each call takes 1 second
const a = await getA();
const b = await getB();

// Concurrent: about 1 second
const [a2, b2] = await Promise.all([getA(), getB()]);

Follow-up questions interviewers ask next

  • What does an async function return if it throws?
  • Why is awaiting inside a for loop sometimes slow?
Q12Medium2–5 years

How do you handle errors with async and await?

30-second answer: Use try/catch around await, because a rejection throws at that line. Promise.all fails fast on the first rejection; use allSettled when you need every result.

In an async function, wrap await calls in try/catch: a rejected promise throws at the await. Without a handler the rejection becomes an unhandled promise rejection, which can crash a Node.js process in current versions and logs an error in browsers.

With Promise.all, the first rejection rejects the whole call and the remaining promises keep running but their results are ignored. Use Promise.allSettled when you need every outcome, and handle errors at a level where you can do something useful, such as retrying or showing a message.

async function loadUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error('HTTP ' + res.status);
    return await res.json();
  } catch (err) {
    console.error('Could not load user', err);
    throw err; // let the caller decide what to show
  }
}

Follow-up questions interviewers ask next

  • What happens to an error in a promise nobody awaits?
  • How would you retry a failed request with backoff?
Q13Medium2–5 years

What is event delegation and why is it useful?

30-second answer: Event delegation puts one listener on a parent and uses bubbling to handle child events, checking event.target. It saves memory and works for elements added later.

Event delegation attaches one listener to a parent element and relies on event bubbling to handle events from its children. Inside the handler you check event.target, or use closest, to find which child was clicked.

It uses less memory than a listener on every child and works for elements added later, such as rows appended to a list. It does not work for events that do not bubble, such as focus and blur (use focusin and focusout), and you must ignore clicks on elements you do not care about.

document.querySelector('#todo-list').addEventListener('click', (event) => {
  const button = event.target.closest('button[data-id]');
  if (!button) return;
  deleteTodo(button.dataset.id);
});

Follow-up questions interviewers ask next

  • Which events do not bubble?
  • What is the difference between event.target and event.currentTarget?
Q14Medium2–5 yearsOften asked

What is the difference between a shallow copy and a deep copy?

30-second answer: A shallow copy shares nested objects with the original; a deep copy duplicates everything. Use structuredClone for a real deep copy, and spread for a shallow one.

A shallow copy duplicates the top level but still shares nested objects, so changing a nested value changes both copies. The spread operator, Object.assign and Array.prototype.slice make shallow copies. A deep copy duplicates every level.

structuredClone(value) is the modern built-in deep copy. It handles dates, maps, sets and circular references, but cannot clone functions. JSON.parse(JSON.stringify(x)) is a common shortcut, but it turns dates into strings and drops undefined, functions and symbols, so use it only for plain data.

const original = { name: 'Asha', address: { city: 'Pune' } };

const shallow = { ...original };
shallow.address.city = 'Delhi';
console.log(original.address.city); // 'Delhi' (shared)

const deep = structuredClone(original);
deep.address.city = 'Mumbai';
console.log(original.address.city); // still 'Delhi'

Follow-up questions interviewers ask next

  • What does JSON.parse(JSON.stringify(x)) lose?
  • How would you update one nested field immutably without a deep copy?
Q15Medium2–5 years

How do ES modules differ from CommonJS?

30-second answer: ES modules use import and export, are statically analysable and asynchronous. CommonJS uses require and module.exports and loads synchronously. ES module exports are live bindings.

ES modules use import and export, are static (imports are analysed before the code runs, which enables tree shaking), load asynchronously and are the standard in browsers and modern Node.js. CommonJS uses require and module.exports, loads synchronously at run time and is the original Node.js module system.

In Node.js a file is treated as an ES module when it uses the .mjs extension or the nearest package.json sets "type": "module". ES module exports are live bindings, whereas a CommonJS export is a plain value on an object, so a primitive you imported does not update when the exporting module changes it.

// ES module
import { add } from './math.js';
export const total = add(1, 2);

// CommonJS
const { add: add2 } = require('./math.cjs');
module.exports = { total: add2(1, 2) };

Follow-up questions interviewers ask next

  • What is tree shaking and why does it need static imports?
  • Can you use require inside an ES module?
Q16EasyFresher

What do map, filter and reduce do, and when would you use a loop instead?

30-second answer: map transforms every element, filter keeps those that pass a test and reduce folds the array into one value. Use a loop when you need to break early or avoid intermediate arrays.

map returns a new array by transforming every element. filter returns a new array containing only the elements that pass a test. reduce folds an array into a single value, such as a sum or an object, using an accumulator.

All three return new values rather than mutating the array, which keeps code predictable. A for loop is better when you need to stop early with break, when you process very large arrays without creating intermediate arrays or when you perform side effects. forEach returns nothing and is meant for side effects only.

const orders = [{ total: 40 }, { total: 15 }, { total: 90 }];
const big = orders.filter((o) => o.total > 30);            // 2 orders
const totals = orders.map((o) => o.total);                 // [40, 15, 90]
const sum = orders.reduce((acc, o) => acc + o.total, 0);   // 145

Follow-up questions interviewers ask next

  • Why must you provide an initial value to reduce?
  • Which of these can you chain, and what does that cost?
Q17EasyFresher

What is the difference between null and undefined, and what do ?. and ?? do?

30-second answer: undefined means no value was assigned; null is an intentional empty value. ?. stops safely at null or undefined, and ?? gives a default only for those two, unlike ||.

undefined means a variable has been declared but not assigned, or a property or argument is missing. null is an intentional empty value that you assign yourself. typeof undefined is "undefined", and typeof null is "object", a historical quirk.

Optional chaining (user?.address?.city) returns undefined instead of throwing when something in the chain is null or undefined. The nullish coalescing operator (??) supplies a default only for null and undefined, unlike ||, which also replaces 0, '' and false.

const count = 0;
count || 10;   // 10 (0 is falsy)
count ?? 10;   // 0  (only null and undefined fall back)

const city = user?.address?.city ?? 'Unknown';

Follow-up questions interviewers ask next

  • Why is typeof null equal to object?
  • When would || give a wrong default but ?? a right one?
Q18HardSenior

What are iterators and generators?

30-second answer: An iterable exposes an iterator whose next() returns value and done. A generator function writes one easily with yield, producing values lazily on demand.

An iterable is an object with a [Symbol.iterator]() method that returns an iterator, an object whose next() method returns { value, done }. for...of, spread and destructuring all consume iterables.

A generator function (function*) is a convenient way to write an iterator: each yield pauses the function and returns a value, and calling next() resumes it. Generators produce values lazily, so you can model infinite sequences or process large data without holding it all in memory.

function* idGenerator() {
  let id = 1;
  while (true) {
    yield id++;
  }
}
const ids = idGenerator();
ids.next().value; // 1
ids.next().value; // 2

Follow-up questions interviewers ask next

  • How does for...of use the iterator protocol?
  • How do async generators differ?
Q19HardSenior

What causes memory leaks in JavaScript and how do you find them?

30-second answer: Leaks come from references you forgot to release: listeners, timers, closures, detached DOM nodes and unbounded caches. Find them by comparing heap snapshots and fix them by cleaning up or using weak references.

A leak happens when memory that is no longer needed stays reachable, so the garbage collector cannot free it. Typical causes are event listeners and timers that are never removed, closures that keep large objects alive, detached DOM nodes still referenced from JavaScript, accidental globals and caches that grow without limit.

To find one, take heap snapshots in the browser DevTools before and after an action, compare them and look at what retains the growing objects. Fixes include removing listeners and clearing timers on cleanup, using WeakMap or WeakRef for caches keyed by objects and putting a size limit on caches.

Follow-up questions interviewers ask next

  • How do WeakMap and WeakSet avoid leaks?
  • How would you spot a leak in a long-running single-page app?
Q20Medium2–5 years

What is currying and partial application?

30-second answer: Currying turns f(a, b, c) into f(a)(b)(c); partial application fixes some arguments in advance. Closures let the returned function remember them.

Currying turns a function that takes several arguments into a chain of functions that each take one, so add(1, 2, 3) becomes add(1)(2)(3). Partial application is related: you fix some arguments up front and get a function that takes the rest.

Both are useful for building reusable, specialised functions from general ones, for example a multiplyBy(2) function that you pass to map. Closures make both work, because the returned function remembers the arguments already supplied.

const multiplyBy = (factor) => (n) => n * factor;

const double = multiplyBy(2);
[1, 2, 3].map(double); // [2, 4, 6]

Follow-up questions interviewers ask next

  • How would you write a generic curry function?
  • Where does currying help in functional pipelines?

How to prepare for a JavaScript interview

  1. Predict output. Write short snippets involving closures in loops, this in callbacks, promise chains mixed with setTimeout and hoisting. Predict the result before running them.
  2. Implement the classics by hand. Debounce, throttle, a promise helper such as Promise.all, deep clone and a simple event emitter come up as live coding tasks.
  3. Understand the event loop visually. Draw the call stack, the microtask queue and the task queue and trace an example through them. It underpins most async questions.
  4. Pair it with a framework. Many frontend interviews continue straight into React questions.
  5. Practise coding problems. Use DSA practice in the language you will interview in.

A frequent mistake is describing behaviour from memory of an article rather than from experience. If you say "microtasks run before macrotasks", be ready to show it with a three-line example.