Skip to main content
Frontend & Core Web

JavaScript Interview Questions

All Levels (Junior to Staff)16 Questions

Comprehensive technical deep dive into JavaScript event loops, closures, prototypical inheritance, V8 JIT optimization, memory leaks, and async microtasks.

22 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice JavaScript Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

How do var, let, and const differ in scoping, hoisting, and the Temporal Dead Zone (TDZ)?

Senior Engineering Answer

var is function-scoped (or global-scoped) and hoisted with an initial value of undefined, allowing reads before its declaration line without throwing. let and const are block-scoped and are also hoisted during lexical environment creation, but they remain uninitialized in the Temporal Dead Zone (TDZ) from the start of the block until their declaration executes; accessing them in the TDZ throws a ReferenceError. const additionally forbids reassigning the binding, though properties of a const object remain mutable.

Production Code Example
function demo() {
  console.log(a); // undefined (var hoisted + initialized)
  // console.log(b); // ReferenceError: Cannot access 'b' before initialization
  var a = 1;
  let b = 2;
  const cfg = { retries: 3 };
  cfg.retries = 5; // valid: mutates object, not the binding
}
Common Interview Trap / Anti-Pattern:

Saying 'let and const are not hoisted' is wrong. In a block containing 'let x = 10', 'typeof x' above the declaration throws a ReferenceError even if an outer 'x' exists, proving the inner binding is hoisted into the TDZ.

Question #2FundamentalJunior

What are the differences between '==', '===', and Object.is() in JavaScript?

Senior Engineering Answer

Loose equality (==) performs Abstract Equality Comparison with implicit type coercion (for example, '' == 0 is true, null == undefined is true). Strict equality (===) skips type coercion and returns false for different types, except it treats NaN === NaN as false and +0 === -0 as true. Object.is() matches === in avoiding coercion, but treats NaN as equal to NaN and distinguishes +0 from -0 (SameValue semantics, used internally by React's useState bailout).

Production Code Example
console.log(0 == false);          // true
console.log(0 === false);         // false
console.log(NaN === NaN);         // false
console.log(Object.is(NaN, NaN)); // true
console.log(+0 === -0);           // true
console.log(Object.is(+0, -0));   // false
Common Interview Trap / Anti-Pattern:

Forgetting that null == undefined is true while null == 0 is false; if you only check 'x == null' intentionally to guard both null and undefined, document it, otherwise prefer '==='.

Question #3FundamentalJunior

How do JavaScript closures work under the hood, and how can they cause memory leaks?

Senior Engineering Answer

A closure is formed when a function retains a reference to its outer lexical environment (the variables in scope where it was defined) even after the outer function has returned. In engines like V8, variables captured by inner functions are heap-allocated inside a Context object rather than popped from the call stack. A memory leak occurs when a long-lived callback (such as a global event listener or setInterval) holds a closure whose shared Context keeps large unused objects (DOM nodes, large buffers) alive and unreachable for cleanup.

Production Code Example
function createRateLimiter(limit) {
  let count = 0;
  return function allow() {
    if (count >= limit) return false;
    count += 1;
    return true;
  };
}

const allowRequest = createRateLimiter(2);
console.log(allowRequest(), allowRequest(), allowRequest()); // true true false
Common Interview Trap / Anti-Pattern:

In V8, sibling closures defined in the same outer scope share one Context object; even if Closure A only uses a small counter, Closure B referencing a huge array keeps that huge array alive as long as Closure A is retained.

Question #4FundamentalJunior

How is the value of 'this' determined in JavaScript functions, and how do arrow functions differ?

Senior Engineering Answer

For regular functions, 'this' is determined dynamically at call time by four rules in precedence order: (1) 'new' binding sets 'this' to the newly constructed object, (2) explicit binding via call/apply/bind forces a specific 'this', (3) implicit binding sets 'this' to the receiver object before the dot (obj.fn()), and (4) default binding sets 'this' to undefined in strict mode (or globalThis in sloppy mode). Arrow functions have no own 'this' binding at all; they capture 'this' lexically from the enclosing scope and cannot be rebound with call/apply/bind or used as constructors.

Production Code Example
const timer = {
  seconds: 0,
  start() {
    // Arrow function inherits 'this' from start()'s receiver (timer)
    setInterval(() => {
      this.seconds += 1;
    }, 1000);
  }
};
Common Interview Trap / Anti-Pattern:

Assigning an object method to a callback reference (const fn = obj.method; setTimeout(fn, 0)) loses implicit binding and makes 'this' undefined in strict mode.

Question #5IntermediateMid

What is the exact execution order between synchronous code, microtasks, requestAnimationFrame, and macrotasks in the browser event loop?

Senior Engineering Answer

First, the currently running synchronous script/macrotask finishes and clears the call stack. Immediately after each macrotask (and after every callback invocation), the engine drains the entire Microtask Queue—including Promise.then/catch/finally reactions, await continuations, queueMicrotask, and MutationObserver callbacks—until empty, even if microtasks enqueue more microtasks. Only once the microtask queue is empty can the browser run a rendering step (firing requestAnimationFrame callbacks before layout/paint if a frame is due) or pick the next macrotask (setTimeout, MessageChannel, UI events).

Production Code Example
console.log("1: sync");
setTimeout(() => console.log("5: macrotask"), 0);
Promise.resolve()
  .then(() => console.log("3: microtask 1"))
  .then(() => console.log("4: microtask 2"));
console.log("2: sync end");
// Output: 1: sync -> 2: sync end -> 3: microtask 1 -> 4: microtask 2 -> 5: macrotask
Common Interview Trap / Anti-Pattern:

An infinite chain of Promise.then() or queueMicrotask() starves rendering and all pending macrotasks completely, freezing browser clicks and paints.

Question #6IntermediateMid

How does JavaScript's prototype chain work, and what does the 'new' operator actually execute?

Senior Engineering Answer

Every JavaScript object has an internal [[Prototype]] link (inspected via Object.getPrototypeOf()). When reading obj.prop, the engine checks obj's own properties first, then walks up [[Prototype]] until it finds the property or reaches null. Calling 'new Fn(...args)' creates a fresh empty object whose [[Prototype]] is set to Fn.prototype, invokes Fn with 'this' bound to that object, and returns the object (unless Fn explicitly returns another non-null object). ES6 class syntax builds directly on this prototype delegation mechanism.

Production Code Example
const protoLogger = {
  log(msg) {
    console.log(`[${this.prefix}] ${msg}`);
  }
};

const apiLogger = Object.create(protoLogger);
apiLogger.prefix = "API";
apiLogger.log("connected"); // [API] connected
console.log(Object.getPrototypeOf(apiLogger) === protoLogger); // true
Common Interview Trap / Anti-Pattern:

Confusing a constructor function's .prototype property (the prototype assigned to instances created by 'new Fn()') with Object.getPrototypeOf(Fn) (which is Function.prototype).

Question #7IntermediateMid

Compare Promise.all, Promise.allSettled, Promise.race, and Promise.any, and show how to cancel in-flight fetch requests with AbortController.

Senior Engineering Answer

Promise.all resolves with an array of values when all promises fulfill, or rejects immediately on the first rejection (fail-fast). Promise.allSettled always waits for every promise and resolves with status objects ({ status: 'fulfilled' | 'rejected' }). Promise.race settles as soon as the first promise either fulfills or rejects. Promise.any resolves with the first fulfillment and only rejects with an AggregateError if every promise rejects. Because Promises themselves have no native cancellation, pair them with AbortController to abort underlying network or async work on timeout or race loss.

Production Code Example
async function fetchWithTimeout(url, ms) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(new Error("Timeout")), ms);
  try {
    const res = await fetch(url, { signal: controller.signal });
    return await res.json();
  } finally {
    clearTimeout(timer);
  }
}
Common Interview Trap / Anti-Pattern:

Promise.race([fetch(url), timeoutPromise]) does NOT cancel the underlying fetch when the timeout wins; without AbortController, the socket and response stream keep running in the background.

Question #8IntermediateMid

When does structuredClone() outperform JSON.parse(JSON.stringify()) for deep cloning, and what can structuredClone() still not clone?

Senior Engineering Answer

JSON round-tripping silently drops undefined, Symbol keys, and functions, converts Date to ISO strings, turns NaN/Infinity into null, destroys Map/Set/RegExp/ArrayBuffer types, and throws on circular references. The built-in structuredClone() API uses the HTML structured clone algorithm, accurately preserving circular references, Date, RegExp, Map, Set, Error, TypedArrays, and ArrayBuffers. However, structuredClone() still throws a DataCloneError on functions, DOM nodes, Symbols, and property descriptors/prototypes (cloning class instances strips their prototype chain).

Production Code Example
const state = {
  createdAt: new Date(),
  tags: new Set(["v8", "dom"]),
  buf: new Uint8Array([1, 2, 3])
};
state.self = state; // circular reference

const copy = structuredClone(state);
console.log(copy.tags instanceof Set); // true
console.log(copy.self === copy);       // true
Common Interview Trap / Anti-Pattern:

Using structuredClone() on class instances drops methods and resets the clone's prototype to Object.prototype; custom class cloning requires explicit toJSON/fromJSON or copy constructors.

Question #9SeniorSenior

How do V8 Hidden Classes (Shapes/Maps) and Inline Caches optimize property access, and what patterns cause deoptimization?

Senior Engineering Answer

Because JavaScript objects are dynamic dictionaries, naive hash-table lookups on every property read would be slow. V8 assigns each object a hidden class (Map/Shape) describing its property layout and memory offsets. When objects initialize the exact same properties in the exact same order, they share one Shape, allowing Inline Caches (ICs) to turn property lookups into single direct memory-offset loads (monomorphic state). Adding properties conditionally in varying orders, deleting properties with 'delete', or passing heterogeneously shaped objects to hot functions shifts call sites from monomorphic to polymorphic (2-4 shapes) or megamorphic (slow hash lookup) and can trigger TurboFan deoptimization.

Production Code Example
// Good: consistent property order keeps one Hidden Class (monomorphic)
function createUser(id, role) {
  return { id, role, active: true };
}

// Anti-pattern: conditional property addition creates divergent transition trees
function createUserBad(id, isAdmin) {
  const u = { id };
  if (isAdmin) u.role = "admin";
  u.active = true;
  return u;
}
Common Interview Trap / Anti-Pattern:

Using 'delete obj.prop' transitions an object to dictionary mode (slow hash-map storage) in V8; setting 'obj.prop = undefined' preserves the fast hidden class layout.

Question #10SeniorSenior

How do detached DOM nodes leak memory in SPAs, and when should you use WeakMap or FinalizationRegistry?

Senior Engineering Answer

A detached DOM tree occurs when an element is removed from the document (element.remove()) while JavaScript still holds a reference to it (or to one of its child nodes, since every DOM node keeps parent/sibling pointers to the entire subtree). V8's Mark-and-Sweep GC cannot reclaim that DOM subtree until the JS reference drops. Storing per-node metadata in a WeakMap keyed by the DOM element avoids holding a strong reference, so once the element leaves the DOM and all strong refs vanish, the entry is reclaimed automatically. FinalizationRegistry registers a cleanup callback after GC reclaims a target, useful for releasing external WASM/handle resources—never for deterministic control flow.

Production Code Example
const elementMetadata = new WeakMap();

function attachTracker(node, data) {
  elementMetadata.set(node, data);
}

// When 'node' is removed from DOM and no strong JS refs remain,
// both 'node' and 'data' become eligible for garbage collection.
Common Interview Trap / Anti-Pattern:

Adding window/document listeners inside a component without removing them on unmount retains the listener closure and any DOM elements captured inside it.

Question #11SeniorSenior

Why should Proxy traps forward operations through Reflect with the receiver argument?

Senior Engineering Answer

When a Proxy intercepts get/set on an object that inherits getters or setters (or whose methods call 'this.otherProp'), forwarding directly via target[prop] binds 'this' inside an inherited getter to the raw target instead of the Proxy, silently bypassing reactivity tracking or validation. Passing Reflect.get(target, prop, receiver) and Reflect.set(target, prop, value, receiver) preserves the Proxy as 'this' inside getters/setters and enforces JS Proxy invariants (such as non-configurable/non-writable property rules) automatically.

Production Code Example
function reactive(target, onRead, onWrite) {
  return new Proxy(target, {
    get(obj, prop, receiver) {
      onRead(prop);
      return Reflect.get(obj, prop, receiver);
    },
    set(obj, prop, value, receiver) {
      const ok = Reflect.set(obj, prop, value, receiver);
      if (ok) onWrite(prop, value);
      return ok;
    }
  });
}
Common Interview Trap / Anti-Pattern:

Wrapping built-ins with internal slots like Map, Set, Date, or private #fields in a naive Proxy throws TypeError ('Method Map.prototype.get called on incompatible receiver') unless methods are bound to target.

Question #12SeniorSenior

How do async iterators (for await...of) and generators simplify streaming paginated APIs or NDJSON responses with natural backpressure?

Senior Engineering Answer

An async generator (async function*) implements Symbol.asyncIterator, yielding Promises that resolve lazily only when the consumer pulls the next item via 'for await...of' or .next(). This creates pull-based backpressure automatically: the producer does not fetch page N+1 or decode the next chunk until the consumer finishes processing item N, avoiding memory buffering of huge result sets.

Production Code Example
async function* streamUsers(baseUrl) {
  let cursor = null;
  do {
    const url = cursor ? `${baseUrl}?cursor=${cursor}` : baseUrl;
    const res = await fetch(url);
    const page = await res.json();
    for (const user of page.items) {
      yield user;
    }
    cursor = page.nextCursor;
  } while (cursor);
}
Common Interview Trap / Anti-Pattern:

Breaking early out of 'for await...of' invokes the generator's .return() method; always place stream reader release calls (reader.releaseLock()) inside a finally block inside the async generator.

Question #13PrincipalStaff

How do you eliminate long tasks and improve Interaction to Next Paint (INP) in CPU-heavy browser JavaScript?

Senior Engineering Answer

Tasks on the main thread exceeding 50ms block input handling and degrade INP. First, move pure computation (parsing, indexing, diffing, cryptography) off the main thread into a Web Worker, passing large ArrayBuffers via Transferable ownership (zero-copy move) or sharing memory with SharedArrayBuffer + Atomics where COOP/COEP headers allow. Second, when work must touch the DOM or main-thread state, chunk loops and yield back to the browser using scheduler.yield() (falling back to setTimeout(..., 0)) so urgent user interactions and paints run between chunks.

Production Code Example
async function processInChunks(items, handleItem) {
  let deadline = performance.now() + 12;
  for (const item of items) {
    handleItem(item);
    if (performance.now() >= deadline) {
      if (globalThis.scheduler?.yield) {
        await scheduler.yield();
      } else {
        await new Promise((r) => setTimeout(r, 0));
      }
      deadline = performance.now() + 12;
    }
  }
}
Common Interview Trap / Anti-Pattern:

Yielding with Promise.resolve() does NOT allow input events or browser paints to run because microtasks drain before the browser yields control back to the event loop.

Question #14PrincipalStaff

How do ES Modules (ESM) live bindings and circular dependencies differ from CommonJS (CJS), and what enables effective tree-shaking?

Senior Engineering Answer

CommonJS require() executes synchronously at runtime and returns a shallow copy (or shared reference) of module.exports at the moment require() runs, meaning circular requires often see partially populated exports and static analysis cannot reliably eliminate unused exports. ES Modules resolve static import/export graphs before execution and expose live read-only bindings (view into the exporting module's variable), so updates in the exporter remain visible to importers and circular imports work when referenced after module initialization. Bundlers tree-shake ESM reliably only when exports are static and package.json declares 'sideEffects': false (or pure /*#__PURE__*/ call annotations) so top-level module evaluation can be safely dropped.

Production Code Example
// Pure factory annotation lets Rollup/esbuild/Webpack drop unused instances
export const defaultClient = /*#__PURE__*/ createHttpClient({ timeout: 5000 });

// Top-level side effect prevents tree-shaking unless marked in package.json
// window.__METRICS__ = initMetrics();
Common Interview Trap / Anti-Pattern:

Re-exporting everything through barrel files (index.ts) inside packages without 'sideEffects: false' often forces bundlers to execute and bundle every imported submodule's side effects.

Question #15PrincipalStaff

Why does 'instanceof Array' fail across iframes or Node vm contexts, and how do you handle cross-realm type checks safely?

Senior Engineering Answer

Every JavaScript realm (main window, iframe, Worker, Node vm.Context) allocates its own distinct global constructors and prototype objects (window.Array !== iframe.contentWindow.Array). Because 'x instanceof Array' walks x's prototype chain looking for the current realm's Array.prototype, arrays created in an iframe return false. Use realm-agnostic checks like Array.isArray(x), Object.prototype.toString.call(x), ArrayBuffer.isView(x), or cross-realm Symbol.for(...) brand tags.

Production Code Example
function isSafeArray(value) {
  return Array.isArray(value);
}

const TYPE_TAG = Symbol.for("acme.Money.v1");
class Money {
  [TYPE_TAG] = true;
  static isMoney(v) {
    return Boolean(v && typeof v === "object" && v[TYPE_TAG] === true);
  }
}
Common Interview Trap / Anti-Pattern:

Using Symbol('tag') instead of Symbol.for('tag') creates a realm-local symbol that still fails equality checks across iframes or duplicate bundled copies of a library.

Question #16PrincipalStaff

How does Prototype Pollution occur in JavaScript applications, and what defenses eliminate it?

Senior Engineering Answer

Prototype pollution occurs when untrusted input controls property keys in recursive object merges, path setters, or query-string parsers—specifically keys like '__proto__', 'constructor', or 'prototype'—mutating Object.prototype globally across the entire runtime. This can bypass auth checks (e.g., user.isAdmin inherited from Object.prototype) or create gadget chains in template engines and Node child_process options. Defenses include explicitly rejecting '__proto__', 'constructor', and 'prototype' keys, checking Object.hasOwn(obj, key) instead of 'in', using Map or Object.create(null) for untrusted dictionaries, and freezing Object.prototype or launching Node with --disable-proto=delete.

Production Code Example
const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);

function safeMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (FORBIDDEN_KEYS.has(key)) continue;
    const srcVal = source[key];
    if (srcVal && typeof srcVal === "object" && !Array.isArray(srcVal)) {
      if (!Object.hasOwn(target, key) || typeof target[key] !== "object") {
        target[key] = {};
      }
      safeMerge(target[key], srcVal);
    } else {
      target[key] = srcVal;
    }
  }
  return target;
}
Common Interview Trap / Anti-Pattern:

Checking 'if (key in target)' instead of 'Object.hasOwn(target, key)' reads inherited properties like 'toString' or 'constructor' from Object.prototype and allows attackers to traverse into Function/Object prototypes.

JavaScript Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This JavaScript preparation set groups 16 prompts across Junior (4), Mid (4), Senior (4), Staff (4) roles with 4 fundamental, 4 intermediate, 4 senior, 4 principal exercises tailored to Frontend & Core Web.

JuniorFundamental

How do var, let, and const differ in scoping, hoisting, and the Temporal Dead Zone (TDZ)?

JuniorFundamental

What are the differences between '==', '===', and Object.is() in JavaScript?

JuniorFundamental

How do JavaScript closures work under the hood, and how can they cause memory leaks?

JuniorFundamental

How is the value of 'this' determined in JavaScript functions, and how do arrow functions differ?

MidIntermediate

What is the exact execution order between synchronous code, microtasks, requestAnimationFrame, and macrotasks in the browser event loop?

MidIntermediate

How does JavaScript's prototype chain work, and what does the 'new' operator actually execute?

Frequently Asked Technical Interview Questions (JavaScript)

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

How does the JavaScript V8 engine optimize execution via Hidden Classes and Inline Caches?
V8 assigns dynamic objects hidden C++ classes (Shapes/Maps) tracking property memory offsets. When objects share the same property layout, Inline Caches (ICs) resolve property reads via direct memory-offset instructions rather than dictionary hash lookups.
What is the exact execution priority between Microtasks and Macrotasks?
After the current synchronous script or macrotask finishes, the event loop drains the entire Microtask Queue (Promise callbacks, queueMicrotask, MutationObserver) until empty before performing a browser paint or dequeuing the next macrotask.
What is the difference between WeakMap and Map for memory management?
A standard Map holds strong references to its keys, preventing garbage collection as long as the Map lives. A WeakMap holds object keys weakly, allowing the key and its associated entry to be garbage collected automatically once no other strong references remain.
How does prototype delegation differ from classical OOP inheritance?
Classical OOP copies class blueprints into fixed layouts at compile time, whereas JavaScript objects link directly to another object via [[Prototype]]. Property reads walk the [[Prototype]] chain dynamically at runtime until resolved or reaching null.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks