Interview Q&A

Pick a topic — languages & databases — 100+ questions and answers in the center column.

JavaScript

Interview questions & answers

Browser & Node — types, async, DOM, ES6+.

102 questions

  1. Question 1

    What is JavaScript?

    A high-level, dynamic language standardized as ECMAScript. It runs in browsers (with the DOM and Web APIs) and on servers with runtimes like Node.js.

    Example code

    console.log(typeof window !== "undefined" ? "browser" : "node");
  2. Question 2

    What is the difference between let, const, and var?

    var is function-scoped and hoisted with an initial undefined; let and const are block-scoped, live in the temporal dead zone until declared, and const cannot be rebound (object contents may still change).

    Example code

    let x = 1;
    const y = 2;
    var z = 3;
    console.log(x + y + z);
  3. Question 3

    What is hoisting?

    Declarations are registered in scope before execution: var becomes undefined until assigned; function declarations are fully initialized early; let/const/class throw if accessed before their line.

    Example code

    console.log(typeof hoist);
    var hoist = 1;
    function hoistFn() {}
  4. Question 4

    What is a closure?

    A function that remembers variables from an enclosing lexical scope after the outer function returns. Used for modules, callbacks, and factories.

    Example code

    function outer() {
      let n = 0;
      return () => ++n;
    }
    const c = outer();
    console.log(c(), c());
  5. Question 5

    How is this determined in JavaScript?

    For normal functions: set by call site (new, method call, call/apply/bind, or global/undefined in a bare call in sloppy/strict mode). Arrow functions inherit this lexically.

    Example code

    const o = {
      name: "a",
      fn() { return this.name; },
    };
    console.log(o.fn());
  6. Question 6

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

    === compares without coercion (type and value). == allows coercion and is easy to misuse; prefer === in almost all code.

    Example code

    console.log(0 == false, 0 === false);
  7. Question 7

    Why does typeof null return "object"?

    A historical implementation artifact kept for backward compatibility. Use value === null to test for null.

    Example code

    console.log(typeof null, null === null);
  8. Question 8

    What are primitive vs reference types?

    Primitives (string, number, boolean, bigint, symbol, undefined, null) are copied by value. Objects, arrays, and functions are references; assignment shares the same identity.

    Example code

    let o = { x: 1 };
    let o2 = o;
    o2.x = 2;
    console.log(o.x);
  9. Question 9

    What is NaN?

    Not-a-Number is a numeric value from invalid math. NaN !== NaN; use Number.isNaN for checks.

    Example code

    console.log(Number.isNaN(NaN), NaN === NaN);
  10. Question 10

    What is the prototype chain?

    Property lookup walks from the object to Object.prototype (and beyond) via [[Prototype]] until a property is found or the chain ends.

    Example code

    const p = { a: 1 };
    console.log(Object.getPrototypeOf(p) === Object.prototype);
  11. Question 11

    What does the class keyword do?

    Syntactic sugar over prototype inheritance: methods on the prototype, static methods on the constructor, extends wires the prototype chain.

    Example code

    class A { m() { return 1; } }
    console.log(new A().m());
  12. Question 12

    What does new do?

    Creates an object linked to Constructor.prototype, runs the constructor with that this, and returns the object unless an object is explicitly returned.

    Example code

    function Box(v) { this.v = v; }
    console.log(new Box(3).v);
  13. Question 13

    What is the event loop?

    Runs JS on one thread: execute the stack, then process microtasks, then macrotasks (timers, I/O), keeping the UI responsive when work is async.

    Example code

    setTimeout(() => console.log("macrotask"), 0);
    Promise.resolve().then(() => console.log("microtask"));
  14. Question 14

    Microtasks vs macrotasks?

    Microtasks (Promise.then, queueMicrotask) run before the next macrotask and can run to completion in a burst. Macrotasks include setTimeout and many I/O callbacks.

    Example code

    Promise.resolve().then(() => console.log("runs before next macrotask"));
  15. Question 15

    What are Promise states?

    Pending, then fulfilled with a value or rejected with a reason. Once settled, state does not change; then/catch return new Promises for chaining.

    Example code

    Promise.resolve(1).then((x) => x + 1).then(console.log);
  16. Question 16

    What is async/await?

    async functions return Promises; await pauses the function until a Promise settles, with errors propagating as rejections unless caught with try/catch.

    Example code

    async function f() {
      return await Promise.resolve(2);
    }
    f().then(console.log);
  17. Question 17

    What is strict mode?

    'use strict' enables stricter parsing and runtime checks: fewer silent errors, no accidental globals in assignments, and more predictable this in functions.

    Example code

    "use strict";
    function g() { return (function () { return this; })(); }
    console.log(g());
  18. Question 18

    What is the temporal dead zone?

    The span from block entry until let/const/class is initialized; reading those bindings throws ReferenceError.

    Example code

    // let x; before use → ReferenceError (TDZ)
    function t() { console.log(typeof undeclared); }
  19. Question 19

    What are call, apply, and bind?

    call/apply invoke a function with an explicit this and arguments (spread vs array). bind returns a new function with a fixed this and optional partial arguments.

    Example code

    function add(a, b) { return a + b; }
    console.log(add.call(null, 1, 2), add.apply(null, [1, 2]));
  20. Question 20

    Debounce vs throttle?

    Debounce runs after input quiets (search boxes). Throttle runs at most once per interval (scroll handlers). Both limit expensive work.

    Example code

    function debounce(fn, ms) {
      let t;
      return (...a) => {
        clearTimeout(t);
        t = setTimeout(() => fn(...a), ms);
      };
    }
  21. Question 21

    What is event delegation?

    Attach one listener on a parent and handle events from children via event.target, reducing listeners and handling dynamic content.

    Example code

    // ul.addEventListener("click", (e) => { if (e.target.matches("li")) { ... } });
  22. Question 22

    Event bubbling vs capturing?

    Events travel capture phase (root to target) then bubble (target to root). stopPropagation and defaultPrevented control flow.

    Example code

    // el.addEventListener("click", handler, { capture: true });
  23. Question 23

    Shallow vs deep copy?

    Shallow copy duplicates top-level fields; nested objects stay shared. Deep copy duplicates nested graphs (structuredClone, libraries, or careful recursion).

    Example code

    const a = { x: { y: 1 } };
    const b = { ...a };
    b.x.y = 9;
    console.log(a.x.y);
  24. Question 24

    map vs forEach?

    map returns a new array of transformed values; forEach returns undefined and is for side effects. map is composable; forEach cannot be chained for results.

    Example code

    console.log([1, 2, 3].map((n) => n * 2));
  25. Question 25

    What is a pure function?

    Same inputs always yield the same output and there are no observable side effects; easier to test and reason about.

    Example code

    const sum = (a, b) => a + b;
    console.log(sum(1, 2));
  26. Question 26

    What is a higher-order function?

    A function that takes functions as arguments or returns a function (e.g. map, filter, reduce, middleware patterns).

    Example code

    const twice = (f) => (x) => f(f(x));
    console.log(twice((x) => x + 1)(0));
  27. Question 27

    What are ES modules?

    import/export static structure enables tree shaking and async loading; distinct from CommonJS require in semantics and loading rules.

    Example code

    // export const x = 1;  // in module
    // import { x } from "./mod.js";
  28. Question 28

    What is tree shaking?

    Bundlers eliminate unused exports when the module graph is statically analyzable, shrinking production bundles.

    Example code

    // unused exports can be dropped when bundler tree-shakes
  29. Question 29

    typeof vs instanceof?

    typeof returns a string type tag for primitives and 'function'/'object'. instanceof tests prototype chain membership for objects.

    Example code

    console.log(typeof 1, [] instanceof Array);
  30. Question 30

    What is JSON?

    A text format for data interchange, a subset of JS literal syntax. JSON.parse/stringify bridge objects and strings; not all JS values round-trip.

    Example code

    const o = { a: 1 };
    console.log(JSON.stringify(o));
  31. Question 31

    What is CORS?

    Browser security policy: cross-origin HTTP requests need server headers allowing the origin (or credentials rules). Same-origin policy blocks reads without permission.

    Example code

    // fetch("/api").then((r) => r.json())
  32. Question 32

    XSS in one sentence?

    Untrusted input rendered as HTML/JS can execute script in a victim's browser; mitigate with escaping, CSP, and safe APIs.

    Example code

    const esc = (s) => s.replace(/</g, "&lt;");
    console.log(esc("<b>"));
  33. Question 33

    What is a Web Worker?

    A separate thread with message passing; no DOM access. Offloads CPU work from the main thread to keep the UI smooth.

    Example code

    // const w = new Worker("worker.js");
    // w.postMessage("ping");
  34. Question 34

    What is the difference between SPA and MPA?

    SPA updates in-page via JS routing and APIs; MPA loads full new documents from the server. Tradeoffs: SEO, complexity, and perceived performance.

    Example code

    // history.pushState({}, "", "/app/route");
  35. Question 35

    npm lockfile purpose?

    Pins transitive dependency versions for reproducible installs across machines and CI (package-lock.json).

    Example code

    // package-lock.json pins dependency tree
  36. Question 36

    What does a bundler do?

    Resolves modules, may transpile, tree-shake, and emit optimized assets for browsers (e.g. Vite, webpack, Rollup).

    Example code

    // vite build / webpack for production bundles
  37. Question 37

    What is Babel?

    A toolchain that transpiles modern JS (and JSX/TS) to older syntax so it runs on older engines per your targets.

    Example code

    // babel transforms modern syntax for older engines
  38. Question 38

    What is hydration?

    In SSR frameworks, attaching client-side listeners and state to server-rendered HTML so the page becomes interactive.

    Example code

    // hydrate client React/Vue on SSR HTML
  39. Question 39

    What is Symbol in JavaScript?

    Unique, non-string property keys; often used for internal metadata that won't collide with string keys.

    Example code

    const k = Symbol("id");
    const user = { [k]: 42, name: "Ann" };
    console.log(user[k]);
  40. Question 40

    What is Iterator in JavaScript?

    Objects with next() following the iterator protocol; consumed by for...of and spread when iterable.

    Example code

    const it = [1, 2][Symbol.iterator]();
    console.log(it.next(), it.next());
  41. Question 41

    What is Generator in JavaScript?

    function* yields values lazily; iterators pause/resume execution and can yield to other generators.

    Example code

    function* gen() {
      yield 1;
      yield 2;
    }
    console.log([...gen()]);
  42. Question 42

    What is Proxy in JavaScript?

    Intercepts operations on an object (get, set, etc.) for logging, validation, or reactive patterns.

    Example code

    const t = new Proxy({}, { get: () => 1 });
    console.log(t.any);
  43. Question 43

    What is Reflect in JavaScript?

    A built-in object with methods mirroring internal operations, often used with Proxy for default behavior.

    Example code

    const o = {};
    Reflect.set(o, "x", 1);
    console.log(o.x);
  44. Question 44

    What is WeakMap in JavaScript?

    Keys are objects only; entries can be GC'd when keys are unreachable—useful for private-ish associations without leaks.

    Example code

    const wm = new WeakMap();
    wm.set({}, 1);
  45. Question 45

    What is WeakSet in JavaScript?

    Like WeakMap but only stores objects in a set; weakly held for caches or tagging without retaining objects.

    Example code

    const ws = new WeakSet();
    ws.add({});
  46. Question 46

    What is BigInt in JavaScript?

    Arbitrary-precision integers; cannot mix with Number in arithmetic without explicit conversion.

    Example code

    const n = 10n ** 20n;
    console.log(n.toString());
  47. Question 47

    What is Optional chaining in JavaScript?

    obj?.prop short-circuits on null/undefined instead of throwing; pairs with ?? for defaults.

    Example code

    const o = { a: null };
    console.log(o.a?.b?.c);
  48. Question 48

    What is Nullish coalescing in JavaScript?

    a ?? b returns b only when a is null or undefined, unlike || which treats many values as falsy.

    Example code

    console.log(0 ?? 1, null ?? 1);
  49. Question 49

    What is Template literals in JavaScript?

    Backtick strings with ${} interpolation and multiline text; tagged templates pass segments to a function.

    Example code

    const n = 3;
    console.log(`two plus one is ${n}`);
  50. Question 50

    What is Destructuring in JavaScript?

    Unpack object properties or array elements into variables, including defaults and rest patterns.

    Example code

    const { a, b = 1 } = { a: 0 };
    const [x, y] = [1, 2];
    console.log(a, b, x, y);
  51. Question 51

    What is Spread operator in JavaScript?

    Expands iterables in arrays, calls, or object literals (own enumerable properties for objects).

    Example code

    console.log([1, ...[2, 3]]);
    console.log({ ...{ a: 1 }, b: 2 });
  52. Question 52

    What is Rest parameters in JavaScript?

    Collect remaining arguments into an array: function f(a, ...rest) { }

    Example code

    function f(a, ...r) { return r.length; }
    console.log(f(1, 2, 3));
  53. Question 53

    What is Object.freeze in JavaScript?

    Makes an object shallowly immutable: cannot add/change/remove own properties (nested objects unaffected unless frozen too).

    Example code

    const o = Object.freeze({ x: 1 });
    // o.x = 2; // silent fail in non-strict
  54. Question 54

    What is Object.assign in JavaScript?

    Copies enumerable own properties from sources to a target; shallow merge pattern for options objects.

    Example code

    console.log(Object.assign({ a: 1 }, { b: 2 }));
  55. Question 55

    What is Array.prototype.flat in JavaScript?

    Flattens nested arrays to a depth; flatMap maps then flattens one level—handy for nested lists.

    Example code

    console.log([[1], [2, [3]]].flat(2));
  56. Question 56

    What is Array.prototype.sort in JavaScript?

    Sorts in place; comparator (a,b) => a-b for numbers. Engine stability and coercion rules matter in interviews.

    Example code

    const a = [10, 2, 1];
    a.sort((x, y) => x - y);
    console.log(a);
  57. Question 57

    What is Set in JavaScript?

    Collection of unique values; fast membership checks; iteration order follows insertion for modern engines.

    Example code

    const s = new Set([1, 1, 2]);
    console.log(s.size);
  58. Question 58

    What is Map in JavaScript?

    Key/value with arbitrary keys (including objects); preserves insertion order; distinct from plain objects for frequent adds/removes.

    Example code

    const m = new Map([["a", 1]]);
    console.log(m.get("a"));
  59. Question 59

    What is Promise.all in JavaScript?

    Fulfills with an array of results when all inputs fulfill; rejects on first rejection.

    Example code

    Promise.all([1, 2].map((x) => Promise.resolve(x))).then(console.log);
  60. Question 60

    What is Promise.allSettled in JavaScript?

    Waits for all to settle; never rejects the aggregate—useful when partial failure is OK.

    Example code

    Promise.allSettled([Promise.resolve(1), Promise.reject(2)]).then(console.log);
  61. Question 61

    What is Promise.race in JavaScript?

    Settles with the first settled input promise—timeouts and racing requests.

    Example code

    Promise.race([new Promise((r) => setTimeout(() => r(1), 50)), Promise.resolve(2)]).then(console.log);
  62. Question 62

    What is queueMicrotask in JavaScript?

    Schedules a microtask; runs before the next macrotask—use sparingly to avoid starvation.

    Example code

    queueMicrotask(() => console.log("micro"));
  63. Question 63

    What is requestAnimationFrame in JavaScript?

    Schedules work before the next repaint; ideal for smooth animations vs setInterval.

    Example code

    requestAnimationFrame(() => console.log("frame"));
  64. Question 64

    What is MutationObserver in JavaScript?

    Watches DOM changes asynchronously; used when integrating with dynamic third-party markup.

    Example code

    // new MutationObserver(cb).observe(el, { childList: true });
  65. Question 65

    What is Intersection Observer in JavaScript?

    Efficiently detects element visibility in the viewport; lazy-loading images and infinite scroll.

    Example code

    // new IntersectionObserver(cb).observe(img);
  66. Question 66

    What is CustomEvent in JavaScript?

    Dispatch structured events on DOM or EventTarget with detail payloads for decoupled components.

    Example code

    const e = new CustomEvent("x", { detail: { id: 1 } });
    dispatchEvent(e);
  67. Question 67

    What is History API in JavaScript?

    pushState/replaceState enable client-side routing without full reloads; popstate handles back/forward.

    Example code

    history.pushState({ id: 1 }, "", "/x");
    window.addEventListener("popstate", () => {});
  68. Question 68

    What is Service Worker in JavaScript?

    Proxy for network/cache offline-first PWA patterns; separate from the page and event-driven.

    Example code

    // navigator.serviceWorker.register("/sw.js");
  69. Question 69

    What is WebSocket in JavaScript?

    Full-duplex persistent connection after HTTP upgrade; low-latency chat and live feeds.

    Example code

    // const ws = new WebSocket("wss://host");
    // ws.onmessage = (e) => console.log(e.data);
  70. Question 70

    What is fetch API in JavaScript?

    Promise-based HTTP; remember to check response.ok and handle JSON/text streams explicitly.

    Example code

    fetch("/api")
      .then((r) => {
        if (!r.ok) throw new Error(String(r.status));
        return r.json();
      })
      .catch(console.error);
  71. Question 71

    What is AbortController in JavaScript?

    Signals cancellation to fetch and other async APIs; abort() rejects with AbortError.

    Example code

    const c = new AbortController();
    fetch("/slow", { signal: c.signal });
    c.abort();
  72. Question 72

    What is Content Security Policy in JavaScript?

    HTTP header restricting script/style sources to mitigate XSS; report-only mode helps rollout.

    Example code

    // Content-Security-Policy: default-src 'self'
  73. Question 73

    What is SameSite in JavaScript?

    Cookie attribute reducing CSRF risk: Strict/Lax/None with Secure for cross-site contexts.

    Example code

    // Set-Cookie: sid=...; SameSite=Lax; Secure
  74. Question 74

    What is localStorage in JavaScript?

    Origin-scoped key/value storage synchronous API; persists until cleared; size limits apply.

    Example code

    localStorage.setItem("k", "v");
    console.log(localStorage.getItem("k"));
  75. Question 75

    What is sessionStorage in JavaScript?

    Like localStorage but scoped to the tab/session lifetime.

    Example code

    sessionStorage.setItem("t", "1");
  76. Question 76

    What is IndexedDB in JavaScript?

    Async structured client database for larger offline datasets; more complex than Storage API.

    Example code

    // indexedDB.open("db", 1)
  77. Question 77

    What is import in JavaScript?

    Dynamic import() returns a Promise of a module; enables code splitting and conditional loading.

    Example code

    const mod = await import("./other.js");
  78. Question 78

    What is Top-level await in JavaScript?

    Allowed in ES modules to await at module load; blocks graph evaluation for that module.

    Example code

    // await fetch("/x") // only valid in ES modules
  79. Question 79

    What is package.json exports in JavaScript?

    Conditional entry points and subpath exports control what consumers can import from a package.

    Example code

    // "exports": { ".": "./index.js" }
  80. Question 80

    What is CommonJS interop in JavaScript?

    Default interop between require and ESM differs by bundler/runtime; __esModule and default export nuances appear in tooling questions.

    Example code

    // const x = require("esm-pkg");
  81. Question 81

    What is Intl in JavaScript?

    Internationalization API for collation, number/date formatting, and locale-aware UI without heavy libraries.

    Example code

    console.log(new Intl.NumberFormat("en-IN").format(1234567));
  82. Question 82

    What is Structured clone in JavaScript?

    structuredClone deep-clones many types (including Map/Set) better than JSON for structured data.

    Example code

    const c = structuredClone(new Map([["a", 1]]));
    console.log(c.get("a"));
  83. Question 83

    What is WeakRef in JavaScript?

    Holds a weak reference to an object; FinalizationRegistry runs callbacks after GC—advanced memory patterns.

    Example code

    let o = { x: 1 };
    const r = new WeakRef(o);
    o = null;
  84. Question 84

    What is Atomics in JavaScript?

    Low-level atomic operations on SharedArrayBuffer for synchronization between workers (niche but asked in specialized roles).

    Example code

    // SharedArrayBuffer + Atomics.add(...)
  85. Question 85

    What is Error causes in JavaScript?

    Error.cause chains underlying errors for clearer async stack traces in modern engines.

    Example code

    throw new Error("outer", { cause: new Error("inner") });
  86. Question 86

    What is Private class fields in JavaScript?

    #field true privacy in classes (not just convention); not visible on the instance object enumeration.

    Example code

    class C {
      #x = 1;
      get x() { return this.#x; }
    }
    console.log(new C().x);
  87. Question 87

    What is Static class blocks in JavaScript?

    Static {} runs once per class evaluation for setup side effects adjacent to class syntax.

    Example code

    class C {
      static x;
      static { this.x = 1; }
    }
  88. Question 88

    What is Temporal (proposal/status) in JavaScript?

    Modern date/time API aiming to replace Date pitfalls; know that Date remains dominant in production today.

    Example code

    // Temporal API — check browser/runtime support
  89. Question 89

    What is SIMD in JavaScript?

    Single-instruction multiple-data for numeric vectors—browser support limited; more common in native/HPC contexts.

    Example code

    // SIMD.js limited; often use WebAssembly for vectors
  90. Question 90

    What is Realms (advanced) in JavaScript?

    Isolated global environments; relevant to secure sandboxing and iframe/worker boundaries in advanced security questions.

    Example code

    // iframe.contentWindow separate realm
  91. Question 91

    What is IIFE in JavaScript?

    Immediately invoked function expression creates a scope; legacy pattern before modules.

    Example code

    (function () {
      const secret = 1;
      console.log(secret);
    })();
  92. Question 92

    What is Memoization in JavaScript?

    Caching results of expensive pure calls; watch memory and cache invalidation.

    Example code

    function memo(fn) {
      const c = new Map();
      return (k) => (c.has(k) ? c.get(k) : c.set(k, fn(k)).get(k));
    }
  93. Question 93

    What is SSR in JavaScript?

    Server renders HTML first for faster first paint and SEO; client hydrates.

    Example code

    // res.send(renderToString(<App />));
  94. Question 94

    What is CSR in JavaScript?

    Client fetches data and renders; simpler hosting, worse first-load SEO without mitigation.

    Example code

    // client-only: root.render(<App />);
  95. Question 95

    What is JWT in JavaScript?

    Self-contained signed tokens for stateless auth; validate signature and expiry; mind XSS storage issues.

    Example code

    // header.payload.signature — verify on server only
  96. Question 96

    What is REST vs GraphQL in JavaScript?

    REST uses multiple resource URLs; GraphQL one endpoint with client-shaped queries—tradeoffs in caching and complexity.

    Example code

    // GET /users/1  vs  POST /graphql { user(id:1){name} }
  97. Question 97

    What is WebAssembly in JavaScript?

    Binary instruction format near-native speed in the browser alongside JS; no DOM access from Wasm directly.

    Example code

    // WebAssembly.instantiate(bytes).then(...)
  98. Question 98

    What is DOMContentLoaded in JavaScript?

    Fires when HTML is parsed; defer long tasks to not block parsing.

    Example code

    document.addEventListener("DOMContentLoaded", () => console.log("ready"));
  99. Question 99

    What is Passive listeners in JavaScript?

    { passive: true } tells the browser scrolling won't be prevented—improves scroll performance.

    Example code

    // addEventListener("touchstart", fn, { passive: true });
  100. Question 100

    What is Lazy loading images in JavaScript?

    loading="lazy" defers offscreen images; improves LCP and bandwidth.

    Example code

    // <img src="x.jpg" loading="lazy" alt="" />
  101. Question 101

    What is Semantic HTML in JavaScript?

    Correct elements (nav, main, article) improve accessibility, SEO, and maintainability.

    Example code

    // <main><article><nav> instead of only <div>
  102. Question 102

    What is ARIA in JavaScript?

    Attributes augment accessibility when native semantics aren't enough; prefer native elements first.

    Example code

    // <button aria-expanded="false">Menu</button>