Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

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
  1. A"object"Correct answer
  2. B"undefined"
  3. C"number"
  4. D"null"

Why: A long-standing quirk of the language.

2Which runs first?Asked almost every time
  1. AIt is random
  2. BsetTimeout callback
  3. CPromise.then callbackCorrect answer
  4. DThey run together

Why: Microtasks run before the next macrotask.

3Which declaration cannot be reassigned?Asked almost every time
  1. Avar
  2. Blet
  3. CconstCorrect answer
  4. Dfunction

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
  1. Abind
  2. Binvoke
  3. CapplyCorrect answer
  4. Dcall

Why: apply takes an array.

5What does x ?? y return when x is 0?Asked almost every time
  1. A0Correct answer
  2. By
  3. Cundefined
  4. Dfalse

Why: Only null or undefined fall back.

6With Promise.all, if one promise rejects…Asked almost every time
  1. AIt returns undefined for that one
  2. BThe whole promise rejectsCorrect answer
  3. CIt is ignored
  4. DAll others are cancelled automatically

Why: Use allSettled to keep each result.

7Arrow functions get this from…Very often asked
  1. ATheir prototype
  2. BThe caller
  3. CThe enclosing scopeCorrect answer
  4. DThe global object always

Why: They have no own this binding.

8Which settles when all promises settle, reporting each result?Very often asked
  1. APromise.allSettledCorrect answer
  2. BPromise.race
  3. CPromise.any
  4. DPromise.all

Why: allSettled never rejects.

9What is 0.1 + 0.2 === 0.3?Very often asked
  1. Atrue
  2. BfalseCorrect answer
  3. CTypeError
  4. DNaN

Why: Floating-point rounding gives 0.30000000000000004.

10Which makes a deep copy of most values?Very often asked
  1. AstructuredCloneCorrect answer
  2. BArray.from
  3. CObject.assign
  4. DSpread syntax

Why: structuredClone copies nested structures.

11What does a generator's next() return?Very often asked
  1. AOnly the value
  2. BA Promise always
  3. CAn array
  4. D{ value, done }Correct answer

Why: The iterator protocol.

12Which creates a private class field?Very often asked
  1. A#countCorrect answer
  2. B_count
  3. Cprivate count in JS
  4. D$count

Why: Real private fields use #.

13Which intercepts property reads on an object?Very often asked
  1. AReflect alone
  2. BProxyCorrect answer
  3. CSymbol
  4. DWeakMap

Why: Handler traps such as get.

14Which returns a sorted copy without changing the original?Very often asked
  1. AtoSorted()Correct answer
  2. Bsort()
  3. Creverse()
  4. Dsplice()

Why: ES2023 immutable method.

15Which is a common cause of memory leaks?Very often asked
  1. AArrow functions
  2. BTemplate literals
  3. CListeners and timers never removedCorrect answer
  4. DUsing const

Why: They keep objects reachable.

16Which method creates a new function with a fixed this?Often asked
  1. Anew
  2. Bcall
  3. Capply
  4. DbindCorrect answer

Why: bind returns a bound function; call and apply invoke immediately.

17What does [1, 2, 3].map(x => x * 2) return?Often asked
  1. Aundefined
  2. B[1, 2, 3]
  3. C[2, 4, 6]Correct answer
  4. D6

Why: map returns a new array of results.

18Accessing a let variable before its declaration…Often asked
  1. AReturns null
  2. BIs allowed in strict mode
  3. CReturns undefined
  4. DThrows a ReferenceErrorCorrect answer

Why: It is in the temporal dead zone.

19Which is NOT a primitive type?Often asked
  1. Astring
  2. Bsymbol
  3. Cbigint
  4. DarrayCorrect answer

Why: Arrays are objects.

20What does forEach return?Often asked
  1. AA new array
  2. BThe original array
  3. CA count
  4. DundefinedCorrect answer

Why: Use map to transform.

21Which deep-copies a Map with nested objects?Often asked
  1. AObject.assign
  2. Bspread syntax
  3. CArray.from
  4. DstructuredCloneCorrect answer

Why: Handles Maps and cycles.

22Which well-known symbol makes an object iterable?Often asked
  1. ASymbol.species
  2. BSymbol.match
  3. CSymbol.iteratorCorrect answer
  4. DSymbol.toPrimitive

Why: Used by for...of.

23null == undefined is…Often asked
  1. ATypeError
  2. BNaN
  3. CtrueCorrect answer
  4. Dfalse

Why: === would be false.

24What does a?.b return if a is null?Often asked
  1. AundefinedCorrect answer
  2. Bnull
  3. CTypeError
  4. Dfalse

Why: Optional chaining short-circuits.

25Which runs JavaScript off the main browser thread?Often asked
  1. ArequestAnimationFrame
  2. BWeb WorkersCorrect answer
  3. CsetTimeout
  4. DPromises

Why: They use postMessage.

26Array.isArray([]) returns…Sometimes asked
  1. Aundefined
  2. Bfalse
  3. CtrueCorrect answer
  4. D"object"

Why: It is the reliable array check.

27Which loop iterates over values of an iterable?Sometimes asked
  1. Afor...in
  2. Bfor...ofCorrect answer
  3. CforEach on objects
  4. Dwhile...in

Why: for...in iterates over keys.

28What does ?? return for 0 ?? 5?Sometimes asked
  1. Afalse
  2. B5
  3. C0Correct answer
  4. Dnull

Why: ?? only falls back on null or undefined.

29What does String.raw do?Sometimes asked
  1. AEncodes HTML
  2. BTrims strings
  3. CParses JSON
  4. DReturns the template's raw text with escapes keptCorrect answer

Why: A built-in tag function.

30Currying transforms f(a, b) into…Sometimes asked
  1. Af([a, b])
  2. Bf.call(a, b)
  3. Cf(b, a)
  4. Df(a)(b)Correct answer

Why: One argument at a time.

Track what you have practised and search every bank in your dashboard.

Start learning