Interview questions with answers
JavaScript interview questions and answers
Closures, this, the event loop, promises, prototypes and modules. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.
- Subjective
- 30
- Objective
- 30
Subjective questions 30
1What is a closure? Give a practical use.Asked almost every time
A closure is a function together with the variables from the scope where it was created, which it keeps access to even after that scope has returned. Uses: private state (a counter whose value only its functions can change), function factories, memoisation, and callbacks that remember their context, such as event handlers in loops.
2Explain the event loop, microtasks and macrotasks.Asked almost every time
JavaScript runs one call stack. When it is empty, the event loop first drains the microtask queue (promise callbacks, queueMicrotask, MutationObserver), then takes one macrotask (timers, I/O, UI events), then drains microtasks again, and in browsers may render. So Promise.resolve().then(...) runs before setTimeout(..., 0).
3How does this work?Asked almost every time
this depends on how a function is called: as a method (obj.fn()) it is the object; called plainly it is undefined in strict mode (the global object otherwise); with new it is the new instance; call, apply and bind set it explicitly. Arrow functions have no own this; they use the surrounding scope's.
4var, let and const: what are the differences?Asked almost every time
var is function-scoped, hoisted and initialised to undefined, and can be redeclared. let and const are block-scoped and hoisted but sit in the temporal dead zone until their declaration runs, so using them earlier throws. const prevents reassignment of the binding, not mutation of the object it points to.
5What are generators and iterators in JavaScript?Asked almost every time
An iterator has next() returning { value, done }; an iterable has [Symbol.iterator](). Generator functions (function*) produce iterators: yield pauses and returns a value, resuming on the next next(). They create lazy sequences and power custom iteration.
6How do you handle errors in async code?Asked almost every time
Use try/catch around await, or .catch() on promise chains. Unhandled rejections are reported (and can crash Node), so always handle them. With Promise.all, one rejection rejects the whole thing; use allSettled when each result matters.
7What is the difference between call, apply and bind?Asked almost every time
All set this. call(thisArg, a, b) invokes immediately with arguments listed; apply(thisArg, [a, b]) invokes with an array; bind(thisArg, a) returns a new function with this (and optionally arguments) fixed for later.
8How does garbage collection work in JavaScript?Asked almost every time
Engines use mark-and-sweep: starting from roots (globals, the stack), they mark reachable objects and free the rest. Memory leaks come from references that stay reachable, such as forgotten timers, global caches, detached DOM nodes held in variables or closures, and unremoved listeners.
9Promises vs. async/await: how do they relate?Very often asked
A promise represents a future value that settles as fulfilled or rejected; .then and .catch handle it. async functions always return promises, and await pauses the function until a promise settles, letting asynchronous code read like synchronous code with try/catch for errors. Use Promise.all to run independent awaits in parallel.
10Explain prototypal inheritance.Very often asked
Every object has an internal prototype link. When a property is missing on the object, JavaScript looks it up along the prototype chain. Classes are syntax over this: methods live on Class.prototype, and extends links the prototypes. Object.create(proto) creates an object with a given prototype directly.
11What is the difference between == and ===?Very often asked
=== compares without type conversion. == converts types first by complex rules ('' == 0 and null == undefined are true). Use === except, by some teams' convention, x == null to check for both null and undefined.
12Debounce vs. throttle?Very often asked
Debounce waits until calls stop for a set time, then runs once: good for search-as-you-type. Throttle runs at most once per interval while calls continue: good for scroll or resize handlers. Both limit how often expensive work runs.
13How do Promise.all, allSettled, race and any differ?Very often asked
all resolves with every result, or rejects at the first rejection. allSettled waits for all and reports each outcome. race settles with the first promise to settle, either way. any resolves with the first fulfilment and rejects only if all reject (AggregateError).
14What are getters, setters and Object.defineProperty?Very often asked
Getters and setters run code when a property is read or written (get fullName() {}). Object.defineProperty sets property descriptors: value, writable, enumerable, configurable or get and set, giving fine control such as read-only properties.
15What are JavaScript classes really?Very often asked
Syntax over prototypes: methods go on Class.prototype, extends sets up the prototype chain, and super calls the parent. Classes add private fields (#count), static members and static blocks, and run in strict mode.
16What are Symbols used for?Very often asked
Unique, non-string property keys that never collide, used for hidden or library-specific properties, and well-known symbols such as Symbol.iterator and Symbol.asyncIterator that customise language behaviour.
17What are Proxy and Reflect?Very often asked
A Proxy wraps an object and intercepts operations (get, set, has, delete) with handler traps, used for validation, reactivity (Vue) or logging. Reflect provides the default behaviour of those operations as functions, convenient inside traps.
18Explain currying and partial application.Very often asked
Currying turns f(a, b, c) into f(a)(b)(c). Partial application fixes some arguments and returns a function waiting for the rest, for example const add5 = add.bind(null, 5). Both help create specialised functions from general ones.
19What is the difference between null and undefined?Very often asked
undefined means a value was not assigned (missing variables, properties or return values). null is an intentional 'no value'. null == undefined is true but === is false; typeof null is 'object' for historical reasons.
20What is event delegation?Often asked
Attaching one listener to a common ancestor and using event.target (often with closest()) to handle events from many children. It relies on bubbling, saves memory, and works for elements added later.
21ES modules vs. CommonJS?Often asked
ES modules use import/export, are static (analysable for tree shaking), load asynchronously and support top-level await. CommonJS uses require/module.exports, loads synchronously and is dynamic. Node supports both; browsers and modern tooling use ES modules.
22What are shallow and deep copies of objects?Often asked
Spread ({...obj}) and Object.assign copy only the top level; nested objects are shared. structuredClone(obj) makes a deep copy of most data types (not functions). JSON.parse(JSON.stringify()) loses dates, undefined and more.
23What are WeakMap and WeakRef for?Often asked
A WeakMap holds keys weakly, so an object used as a key can still be garbage-collected; useful for caching data about objects without leaking memory. WeakRef holds a weak reference to an object, rarely needed and with unpredictable timing.
24How do optional chaining and nullish coalescing work?Often asked
a?.b?.c returns undefined instead of throwing if something along the way is null or undefined; it also works for calls fn?.(). x ?? y returns y only when x is null or undefined, unlike ||, which also replaces 0, '' and false.
25What are tagged template literals?Often asked
A function placed before a template literal receives the string parts and the interpolated values separately, so it can escape, translate or build things like SQL or CSS safely, as in styled-components or String.raw.
26What is the difference between map, forEach, filter and reduce?Often asked
map returns a new array of transformed items; forEach runs a function for side effects and returns undefined; filter returns items that pass a test; reduce folds the array into one value such as a sum or object.
27What are immutable array methods added in ES2023?Often asked
toSorted, toReversed, toSpliced and with(index, value) return new arrays instead of changing the original, avoiding accidental mutation that is common with sort and reverse.
28What is structuredClone?Often asked
A built-in function that deep-copies values including nested objects, arrays, Dates, Maps, Sets and circular references. It cannot clone functions, DOM nodes or class prototypes (instances become plain objects).
29What is hoisting?Sometimes asked
Declarations are processed before code runs: function declarations are fully hoisted (callable before their line), var declarations are hoisted as undefined, and let, const and class are hoisted but inaccessible until declared (temporal dead zone).
30What are Web Workers?Sometimes asked
Background threads in the browser that run scripts without blocking the UI, communicating with the main thread through postMessage. They suit heavy computation but cannot access the DOM directly.
Objective questions 30
1What does typeof null return?Asked almost every time
Why: A long-standing quirk of the language.
2Which runs first?Asked almost every time
Why: Microtasks run before the next macrotask.
3Which declaration cannot be reassigned?Asked almost every time
Why: const bindings cannot be reassigned, though objects can be mutated.
4Which invokes a function immediately with an array of arguments?Asked almost every time
Why: apply takes an array.
5What does x ?? y return when x is 0?Asked almost every time
Why: Only null or undefined fall back.
6With Promise.all, if one promise rejects…Asked almost every time
Why: Use allSettled to keep each result.
7Arrow functions get this from…Very often asked
Why: They have no own this binding.
8Which settles when all promises settle, reporting each result?Very often asked
Why: allSettled never rejects.
9What is 0.1 + 0.2 === 0.3?Very often asked
Why: Floating-point rounding gives 0.30000000000000004.
10Which makes a deep copy of most values?Very often asked
Why: structuredClone copies nested structures.
11What does a generator's next() return?Very often asked
Why: The iterator protocol.
12Which creates a private class field?Very often asked
Why: Real private fields use #.
13Which intercepts property reads on an object?Very often asked
Why: Handler traps such as get.
14Which returns a sorted copy without changing the original?Very often asked
Why: ES2023 immutable method.
15Which is a common cause of memory leaks?Very often asked
Why: They keep objects reachable.
16Which method creates a new function with a fixed this?Often asked
Why: bind returns a bound function; call and apply invoke immediately.
17What does [1, 2, 3].map(x => x * 2) return?Often asked
Why: map returns a new array of results.
18Accessing a let variable before its declaration…Often asked
Why: It is in the temporal dead zone.
19Which is NOT a primitive type?Often asked
Why: Arrays are objects.
20What does forEach return?Often asked
Why: Use map to transform.
21Which deep-copies a Map with nested objects?Often asked
Why: Handles Maps and cycles.
22Which well-known symbol makes an object iterable?Often asked
Why: Used by for...of.
23null == undefined is…Often asked
Why: === would be false.
24What does a?.b return if a is null?Often asked
Why: Optional chaining short-circuits.
25Which runs JavaScript off the main browser thread?Often asked
Why: They use postMessage.
26Array.isArray([]) returns…Sometimes asked
Why: It is the reliable array check.
27Which loop iterates over values of an iterable?Sometimes asked
Why: for...in iterates over keys.
28What does ?? return for 0 ?? 5?Sometimes asked
Why: ?? only falls back on null or undefined.
29What does String.raw do?Sometimes asked
Why: A built-in tag function.
30Currying transforms f(a, b) into…Sometimes asked
Why: One argument at a time.
Track what you have practised and search every bank in your dashboard.
Start learning