Skip to content
Tech Interview Prep
Technical interview guide

JavaScript Fundamentals

Values and references, the four equality algorithms, scope and closures, this and arrow functions, prototypes and classes, the event loop, and modules.

Read
46 min
Practice MCQs
25
Interview Q&A
25
Edition
v2
Editorial status
Reviewed
Relevant for
Frontend Engineer

Scope: ECMAScript 2024 and later, with Node behaviour cited from the active Node.js LTS line and browser behaviour from the WHATWG HTML event loop.

Curated: · Written: · Reviewed:

25 questions

MCQ-10A script's first statement is `console.log(f, g)`. Later in the same script come `function f() {}` and `const g = function () {};`. Run under Node (V8), it throws `ReferenceError: Cannot access 'g' before initialization`. Which statement describes the two bindings at the moment the first statement runs?
MCQ-9A Node 20 service runs this on startup: ```js function init() { console.log(timeout); const timeout = 5000; return timeout; } init(); ``` The call throws. Which statement explains the throw and what the same code would do if `const timeout = 5000` were changed to `var timeout = 5000`?
MCQ-11A module builds a list of closures and calls one of them before and after mutating the loop variable: ```js function build() { var i; const fns = []; for (i = 0; i < 3; i++) { fns.push(() => i); } const first = fns[0](); i = 100; const second = fns[0](); return [first, second]; } console.log(build()); ``` What does it log?
MCQ-12An engineer profiles a Node.js process and sees retained heap growing over time. A request handler declares a counter and a 40 MB buffer, creates a closure that reads both, and stores the closure on a module-level event emitter. The handler increments the counter after creating the closure, and the closure later reads the incremented value. The handler returns and the process keeps running. A heap snapshot shows the buffer still reachable, while a second 40 MB buffer declared in the same handler scope and referenced by no closure has been collected. Which mechanism describes how closures retain memory, and which condition creates the unintended leak?
MCQ-1A team is reviewing a shared-counter helper before it ships. The snippet below runs in Node.js 20. What does the final `console.log` print? ```js function bump(counter) { counter.count += 1; counter = { count: 100 }; counter.count += 1; } const a = { count: 0 }; const b = a; bump(a); bump(b); console.log(a.count, b.count, a === b, a === { count: 2 }); ```
MCQ-19A Node 20 service keeps a config object in memory. Three copies are made from it: ```js const cached = { retries: 3, hosts: ['a'], startedAt: new Date(0) }; const spread = { ...cached }; spread.hosts.push('b'); const deep = structuredClone(cached); deep.hosts.push('c'); const viaJson = JSON.parse(JSON.stringify(cached)); viaJson.hosts.push('d'); ``` After all three run, what are `cached.hosts` and `typeof viaJson.startedAt`?
MCQ-18A service builds its config once at startup with `const cfg = { ...baseConfig };` from: ```js let currentTimeout = 2000; const baseConfig = { get timeoutMs() { return currentTimeout; }, }; Object.defineProperty(baseConfig, 'region', { value: 'eu-west-1', enumerable: false }); ``` A later reload sets `currentTimeout = 5000`. Requests still time out at 2000 ms and `cfg.region` is `undefined`. Which explanation fits both symptoms?
MCQ-16Given `const proto = { n: 1, tag: 'base' }; const o = Object.create(proto); o.n = 2; const p = Object.create(o);`, what does `console.log(p.n, p.tag, proto.n, Object.hasOwn(p, 'n'), Object.hasOwn(o, 'n'))` print?
MCQ-13A module runs this code: ```js const proto = { m() { return this; } }; const o = Object.create(proto); const f = o.m; ``` What do `o.m()` and `f()` return, in that order?
MCQ-14Given this class, what does `new Ticker().run()` do? ```js class Ticker { constructor() { this.ticks = 0; } run() { [1, 2, 3].forEach(function () { this.ticks += 1; }); return this.ticks; } } ```
MCQ-15The snippet below calls the same function through `call`, `apply`, and a function returned by `bind`. What does it log? ```js const log = []; function f(a, b) { log.push(`${this.id}:${a}:${b}`); } const o1 = { id: 'o1' }, o2 = { id: 'o2' }; const b = f.bind(o1, 'x'); f.call(o2, 'y', 'z'); f.apply(o1, ['p', 'q']); b.call(o2, 'w'); console.log(log.join('|')); ```
MCQ-17A team is auditing a widget class before it ships. The `inc` field is an arrow function because the handler gets detached and passed to `addEventListener`; `bump` is a normal method. Two instances are created and the detached handler is called once. What does the final `console.log` print? ```js class Counter { count = 0; inc = () => ++this.count; bump() { return ++this.count; } } const a = new Counter(); const b = new Counter(); const f = a.inc; console.log(f(), a.count, b.count, a.bump === b.bump, a.inc === b.inc); ```
MCQ-4A service loads its settings from svc.json, which contains exactly `{"timeoutMs": 0, "retries": 0}` and no `tag` key. The loader is: ```js const raw = JSON.parse(fs.readFileSync("svc.json", "utf8")); const cfg = { timeoutMs: raw.timeoutMs ?? 3000, retries: raw.retries || 2, tag: raw.tag ?? "prod", }; ``` What is `cfg`?
MCQ-5A service reads this file at boot: ```json {"maxRetries": 0, "blockedIds": [], "region": ""} ``` The loader is: ```js const cfg = JSON.parse(fs.readFileSync('svc.json', 'utf8')); const maxRetries = cfg.maxRetries || 3; const blockedIds = cfg.blockedIds || ['ALL']; const region = cfg.region || 'default'; ``` The operator set those three values to disable retries, block nothing, and pin no region. Which triple does the loader bind?
MCQ-6A Node 20 service reads a refund flag with `const refund = new URL(req.url, 'http://x').searchParams.get('refund');` and then runs `if (refund == 0) { skipRefund(); }`. `get` returns a string when the key is present and null when it is absent. QA sends four requests: `?refund=0`, `?refund=` (key present, empty value), `?refund=false`, and one with no `refund` key at all. Which requests reach `skipRefund()`?
MCQ-7A telemetry pipeline dedupes readings with `[...new Set(readings)]`. A reviewer replaces it with `readings.filter((v, i) => readings.indexOf(v) === i)`, arguing the two are equivalent. The readings can contain NaN (a failed sensor parse) and -0 (signed-zero arithmetic). For `readings = [NaN, NaN, 0, -0, 1]`, what does each version return?
MCQ-8How does the ECMAScript ToPrimitive abstract operation resolve an ordinary object to a primitive value during implicit coercion?
MCQ-2A ledger keeps transaction IDs in a Postgres bigint column and serves them to a Node 20 reconciler as JSON numbers. One batch contains the distinct IDs 9007199254740992, 9007199254740993 and 9007199254740994, and the report built from that batch lists two transactions. The client runs: ```js const ids = JSON.parse('[9007199254740992,9007199254740993,9007199254740994]'); const unique = new Set(ids); ``` Which account of that batch is right, and which fix keeps every ID?
MCQ-3A chat client truncates display names to 8 UTF-16 code units with `name.slice(0, 8)` before rendering. A user whose display name is `Ravi 🎉🎉` reports that the rendered name contains a replacement character (``). U+1F389 is outside the BMP and is stored as a surrogate pair. Which diagnosis and fix is right?
MCQ-20A rate limiter on Node.js 20 pre-sizes a counter array, then a late batch backfills one slot: const hits = new Array(3); hits[4] = 7; hits.length = 3; console.log(JSON.stringify(hits)); console.log(hits.length, hits.filter(() => true).length); What does this print?
MCQ-21A worker pulls work items out of a queue through a generator, then wants a second pass over the leftovers: ```js function* consume(queue) { while (queue.length > 0) yield queue.shift(); } const q = [1, 2, 3, 4]; const it = consume(q); const head = [...it].slice(0, 2); const rest = [...it]; ``` Which account of the run is correct?
MCQ-22A page's init script runs the following, and a smoke test asserts on the recorded console output: ```js console.log("start"); setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => { console.log("then-1"); queueMicrotask(() => console.log("micro-2")); }); queueMicrotask(() => console.log("micro-1")); console.log("end"); ``` Which order does the console show?
MCQ-23On Node 20, this handler runs once. What does the process print and do? ```js function fail() { return Promise.reject(new Error("db down")); } async function handle() { try { fail().then(() => console.log("ok")); } catch (e) { console.log("caught:" + e.message); } console.log("done"); } handle(); ```
MCQ-24A Node 20 service builds a report from 12 profile IDs; each `fetchRow(id)` takes about 250 ms of network wait. The handler is: ```js async function buildReport(ids) { const rows = []; ids.forEach(async (id) => { rows.push(await fetchRow(id)); }); return rows; } ``` The endpoint returns `buildReport(ids)`. What does the caller receive, and roughly when?
MCQ-25Node 20, with `"type": "module"` in package.json. Two files form a cycle: ```js // a.mjs import { getB } from "./b.mjs"; export let a = 1; console.log(getB()); // b.mjs import { a } from "./a.mjs"; export function getB() { return a + 10; } ``` You run `node a.mjs`. What does it print?