Pick a topic — languages & databases — 100+ questions and answers in the center column.
JavaScript
Browser & Node — types, async, DOM, ES6+.
102 questions
Question 1
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");Question 2
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);Question 3
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() {}Question 4
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());Question 5
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());Question 6
=== 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);Question 7
A historical implementation artifact kept for backward compatibility. Use value === null to test for null.
Example code
console.log(typeof null, null === null);Question 8
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);Question 9
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);Question 10
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);Question 11
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());Question 12
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);Question 13
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"));Question 14
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"));Question 15
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);Question 16
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);Question 17
'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());Question 18
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); }Question 19
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]));Question 20
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);
};
}Question 21
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")) { ... } });Question 22
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 });Question 23
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);Question 24
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));Question 25
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));Question 26
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));Question 27
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";Question 28
Bundlers eliminate unused exports when the module graph is statically analyzable, shrinking production bundles.
Example code
// unused exports can be dropped when bundler tree-shakesQuestion 29
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);Question 30
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));Question 31
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())Question 32
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, "<");
console.log(esc("<b>"));Question 33
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");Question 34
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");Question 35
Pins transitive dependency versions for reproducible installs across machines and CI (package-lock.json).
Example code
// package-lock.json pins dependency treeQuestion 36
Resolves modules, may transpile, tree-shake, and emit optimized assets for browsers (e.g. Vite, webpack, Rollup).
Example code
// vite build / webpack for production bundlesQuestion 37
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 enginesQuestion 38
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 HTMLQuestion 39
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]);Question 40
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());Question 41
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()]);Question 42
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);Question 43
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);Question 44
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);Question 45
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({});Question 46
Arbitrary-precision integers; cannot mix with Number in arithmetic without explicit conversion.
Example code
const n = 10n ** 20n;
console.log(n.toString());Question 47
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);Question 48
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);Question 49
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}`);Question 50
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);Question 51
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 });Question 52
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));Question 53
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-strictQuestion 54
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 }));Question 55
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));Question 56
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);Question 57
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);Question 58
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"));Question 59
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);Question 60
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);Question 61
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);Question 62
Schedules a microtask; runs before the next macrotask—use sparingly to avoid starvation.
Example code
queueMicrotask(() => console.log("micro"));Question 63
Schedules work before the next repaint; ideal for smooth animations vs setInterval.
Example code
requestAnimationFrame(() => console.log("frame"));Question 64
Watches DOM changes asynchronously; used when integrating with dynamic third-party markup.
Example code
// new MutationObserver(cb).observe(el, { childList: true });Question 65
Efficiently detects element visibility in the viewport; lazy-loading images and infinite scroll.
Example code
// new IntersectionObserver(cb).observe(img);Question 66
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);Question 67
pushState/replaceState enable client-side routing without full reloads; popstate handles back/forward.
Example code
history.pushState({ id: 1 }, "", "/x");
window.addEventListener("popstate", () => {});Question 68
Proxy for network/cache offline-first PWA patterns; separate from the page and event-driven.
Example code
// navigator.serviceWorker.register("/sw.js");Question 69
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);Question 70
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);Question 71
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();Question 72
HTTP header restricting script/style sources to mitigate XSS; report-only mode helps rollout.
Example code
// Content-Security-Policy: default-src 'self'Question 73
Cookie attribute reducing CSRF risk: Strict/Lax/None with Secure for cross-site contexts.
Example code
// Set-Cookie: sid=...; SameSite=Lax; SecureQuestion 74
Origin-scoped key/value storage synchronous API; persists until cleared; size limits apply.
Example code
localStorage.setItem("k", "v");
console.log(localStorage.getItem("k"));Question 75
Like localStorage but scoped to the tab/session lifetime.
Example code
sessionStorage.setItem("t", "1");Question 76
Async structured client database for larger offline datasets; more complex than Storage API.
Example code
// indexedDB.open("db", 1)Question 77
Dynamic import() returns a Promise of a module; enables code splitting and conditional loading.
Example code
const mod = await import("./other.js");Question 78
Allowed in ES modules to await at module load; blocks graph evaluation for that module.
Example code
// await fetch("/x") // only valid in ES modulesQuestion 79
Conditional entry points and subpath exports control what consumers can import from a package.
Example code
// "exports": { ".": "./index.js" }Question 80
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");Question 81
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));Question 82
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"));Question 83
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;Question 84
Low-level atomic operations on SharedArrayBuffer for synchronization between workers (niche but asked in specialized roles).
Example code
// SharedArrayBuffer + Atomics.add(...)Question 85
Error.cause chains underlying errors for clearer async stack traces in modern engines.
Example code
throw new Error("outer", { cause: new Error("inner") });Question 86
#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);Question 87
Static {} runs once per class evaluation for setup side effects adjacent to class syntax.
Example code
class C {
static x;
static { this.x = 1; }
}Question 88
Modern date/time API aiming to replace Date pitfalls; know that Date remains dominant in production today.
Example code
// Temporal API — check browser/runtime supportQuestion 89
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 vectorsQuestion 90
Isolated global environments; relevant to secure sandboxing and iframe/worker boundaries in advanced security questions.
Example code
// iframe.contentWindow separate realmQuestion 91
Immediately invoked function expression creates a scope; legacy pattern before modules.
Example code
(function () {
const secret = 1;
console.log(secret);
})();Question 92
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));
}Question 93
Server renders HTML first for faster first paint and SEO; client hydrates.
Example code
// res.send(renderToString(<App />));Question 94
Client fetches data and renders; simpler hosting, worse first-load SEO without mitigation.
Example code
// client-only: root.render(<App />);Question 95
Self-contained signed tokens for stateless auth; validate signature and expiry; mind XSS storage issues.
Example code
// header.payload.signature — verify on server onlyQuestion 96
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} }Question 97
Binary instruction format near-native speed in the browser alongside JS; no DOM access from Wasm directly.
Example code
// WebAssembly.instantiate(bytes).then(...)Question 98
Fires when HTML is parsed; defer long tasks to not block parsing.
Example code
document.addEventListener("DOMContentLoaded", () => console.log("ready"));Question 99
{ passive: true } tells the browser scrolling won't be prevented—improves scroll performance.
Example code
// addEventListener("touchstart", fn, { passive: true });Question 100
loading="lazy" defers offscreen images; improves LCP and bandwidth.
Example code
// <img src="x.jpg" loading="lazy" alt="" />Question 101
Correct elements (nav, main, article) improve accessibility, SEO, and maintainability.
Example code
// <main><article><nav> instead of only <div>Question 102
Attributes augment accessibility when native semantics aren't enough; prefer native elements first.
Example code
// <button aria-expanded="false">Menu</button>