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.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v3
Editorial status
Reviewed

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.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain values against references and how it changes a production decision.

Answer

The 90-second answer. A binding holds a value. For primitives that value is the data itself; for objects, arrays and functions it is a reference to a heap object. Assignment, argument passing and === all operate on that value, so passing an object passes the reference by value: the callee can mutate the object the caller sees, but cannot rebind the caller's variable. The production consequence is aliasing: two parts of the system that each believe they own a value are sharing one, and a write in one shows up in the other.

JavaScript
// Node 20, strict mode
function mutate(o) { o.n = 2; }
function rebind(o)  { o = { n: 3 }; }

const box = { n: 1 };
mutate(box);   // box.n === 2
rebind(box);   // box.n === 2 — the parameter was rebound, not the caller's binding

A shallow copy stops at the top level, which is where most of the surprises live:

JavaScript
const base = { n: 1, tags: ['a'] };
const shallow = { ...base };
shallow.n = 2;            // base.n still 1
shallow.tags.push('b');   // base.tags is now ['a', 'b'] — the array was shared

Failure modes, and how you catch each.

  1. State mutation that never re-renders. items.push(x); setItems(items) passes the same reference, React's Object.is check bails out, and the UI stays stale while the store's array is correct. Detect: React DevTools Profiler shows no commit for the dispatch.
  2. Identity-keyed cache that never hits. cache.set(req, result) where req is rebuilt per call gives a 0% hit rate and unbounded growth. Detect: cache size climbs linearly with request count while the hit-rate metric sits flat at 0.
  3. structuredClone on a class instance. It returns a plain object, so structuredClone(new Conn()).ping() throws TypeError: ... is not a function; it also throws DataCloneError on functions. Detect: a unit test that clones a fixture and calls a method on it.
  4. Object.freeze is shallow. Object.freeze({ db: { pool: 10 } }) still allows cfg.db.pool = 20: silently in sloppy mode, TypeError in strict mode. Detect: strict mode plus a test that writes to a nested field.

Trade-offs.

ApproachCostWins whenLoses when
Mutate in placeO(1) memoryhot loop over a buffer you ownthe value crosses a boundary you don't control
Shallow copy ({...o}, Object.assign)O(top-level keys)flat config/state objects, React updatesnested objects are still shared
structuredClone (Node 17+, evergreen browsers)O(total nodes) time and memoryworker/thread boundary, cycles, Map/Set/Datefunctions, class instances (prototype lost), large graphs
Object.freezeno copydev-time guard on a constantshallow only; nested writes still land

Worked arithmetic, hypothetical but the shape is real: a 50k-node graph cloned per request at 1k rps allocates 50M nodes per second. That is the case for cloning once at startup and freezing, not per request.

The decision. Name the contract in the function name, mutateX versus withX, and copy at the boundary where ownership changes: worker postMessage, cache insert, setState. Freeze config at startup. Reach for structuredClone when the graph has cycles or Map/Set; write a hand-rolled copy when it has methods you need to keep.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does null against undefined guarantee, and what does it deliberately leave open?

Answer

The guarantee is mechanical and narrow; the meaning is left open.

null and undefined are two distinct types, Null and Undefined, each with exactly one value. The spec fixes how they compare and how a few operators treat them. It fixes nothing about what they mean.

What is guaranteed:

  • null == undefined is true; null === undefined is false. The loose-equality algorithm has a dedicated clause: if one operand is null and the other undefined, return true. No coercion to number, no ToPrimitive.
  • They are the only two values that loosely equal each other. null == 0, null == "", undefined == 0 are all false. So x == null is a precise "is absent" test.
  • typeof null === "object" (the ES1 bug, preserved), typeof undefined === "undefined".
  • Both are falsy, and ?? and ?. group them into one set, "nullish", while || and truthiness do not.
JavaScript
typeof null        // "object"
typeof undefined   // "undefined"
null == undefined  // true
null === undefined // false
null == 0          // false
undefined == ""    // false
0 ?? 8080          // 0
0 || 8080          // 8080

One carve-out: document.all == null is also true. It is the only object with that behavior (the HTML spec's [[IsHTMLDDA]]), so in a browser x == null means "null, undefined, or document.all".

What is deliberately left open:

The spec never says null means "intentional absence" and undefined means "accidental". That split is convention, widely followed, not a guarantee. Nothing stops an API from returning null for a missing record and undefined for a missing field, or the reverse.

More concretely, undefined conflates two states the language will not separate for you: a property that was never set, and a property set to undefined.

JavaScript
const o = { a: undefined };
o.a == null   // true
o.b == null   // true
'a' in o      // true
'b' in o      // false

o.a and o.b are indistinguishable by value; only in (or hasOwnProperty) tells them apart.

Serialization is where the open choice bites. JSON has no undefined: JSON.stringify drops undefined-valued properties and turns undefined inside an array into null, while null round-trips.

JavaScript
JSON.stringify({ a: null, b: undefined })  // '{"a":null}'
JSON.stringify([null, undefined])          // '[null,null]'

A field that is absent as undefined disappears from the payload; a field that is null survives as null. If a consumer distinguishes them, the choice you left open becomes a wire-format decision.

Practical rule: pick one to mean absent in your own data and document it, use == null when either should pass, and use ?? rather than || when 0 or "" are valid values.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe the falsy set and truthiness and the evidence you would collect before relying on it.

Answer

The 60-second answer

Eight values are falsy: false, 0, -0, 0n, "", null, undefined, NaN. Everything else is truthy, including [], {}, "0", " ", "false", and new Boolean(false). A condition applies ToBoolean (ECMA-262 §7.1.2), which is a fixed lookup table: no valueOf, no toString, no user code runs.

Before I let truthiness decide anything, I collect three pieces of evidence: the spec anchor for the value's type, the actual distribution of values reaching that branch (instrumented, not assumed), and a test that pins the boundary case (empty collection, zero, empty string) the branch is supposed to distinguish.

Mechanism

ToBoolean is total and side-effect free. Abstract equality (==) is the opposite: it runs a coercion chain, so [] == false and Boolean([]) disagree. That gap is where the bugs live.

JavaScript
Boolean([]);                 // true  — object, ToBoolean is true
Boolean("0");                // true  — non-empty string
Boolean("");                 // false
Boolean(new Boolean(false)); // true  — object wrapper
[] == false;                 // true  — [] -> "" -> 0, false -> 0
[1] == false;                // false — [1] -> "1" -> 1, 1 != 0
null == false;               // false — null only loosely equals undefined

Trace of [] == false: boolean operand converts to ToNumber(false) = 0; object vs number converts ToPrimitive([]) = "", then ToNumber("") = 0; 0 == 0 is true. null == false skips that path: null is loosely equal only to undefined.

valueBoolean(v)v == falsecheck that means what it says
0falsetruev === 0
-0falsetrueObject.is(v, -0)
0nfalsetruev === 0n
""falsetruev === ""
nullfalsefalsev === null
undefinedfalsefalsev === undefined
NaNfalsefalseNumber.isNaN(v)
[]truetruev.length === 0
{}truefalseObject.keys(v).length === 0
"0"truetruev === "0"
" "truetruev.trim() === ""

Failure modes and how they are detected

  • Empty collection passes if (arr), so an empty result takes the same branch as a full one. Detect with a test that feeds [] and asserts which branch ran.
  • 0 is a legitimate value (count, offset, port, price) and gets read as absent. The classic form is const limit = opts.limit || 10, which turns a caller's limit: 0 into 10; ?? keeps it. Detect with a boundary test at 0.
  • "false" from an env var or JSON is truthy. Detect by parsing explicitly (v === "true") rather than testing the string.
  • == false / == 0 comparisons. Detect with ESLint eqeqeq.

Evidence checklist

  • Spec: ECMA-262 §7.1.2 ToBoolean; the falsy list is normative and unchanged since ES1, with 0n added in ES2020. One host quirk: Annex B [[IsHTMLDDA]] makes document.all falsy in browsers while typeof document.all === "undefined". Bounded to browser hosts, absent in Node.
  • Engine check: run the exact expressions on the runtimes you ship to. Truthiness itself does not vary; document.all does.
  • Instrument the branch: log typeof v plus a JSON-safe rendering at the condition, or count how often the falsy branch is taken in staging. The evidence that matters is the input distribution, not the operator.
  • Static: eqeqeq kills == false; @typescript-eslint/strict-boolean-expressions flags truthiness on non-boolean types; no-implicit-coercion catches !!-style shortcuts.
  • Tests: table-driven over the boundary values above, plus one test per branch driven by the empty/zero input.

Test the property you mean (length for collections, an explicit null check for absence) and keep loose comparisons with booleans out of the codebase.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on loose equality against strict equality. How do you evaluate it?

Answer

What I'd say first. == isn't undefined behaviour, ECMAScript fully specifies it (the IsLooselyEqual algorithm), so the review question isn't "is it safe", it's "is the coercion the semantics the design intends, and does it hold for every input the boundary admits?" I'd ask the teammate to name the exact case they're relying on. If it's x == null to catch both null and undefined, that's a deliberate, documented idiom and I'd leave it. If it's anything else (normalising a string from JSON.parse, a query param, or an env var against a number) I'd ask for === plus one explicit conversion where the data enters, because the coercion is doing work the reader can't see, and the type of the input is exactly what changes between environments.

The mechanism, in order. For x == y:

  1. Same type → strict comparison, no conversion.
  2. null/undefined → equal to each other and to nothing else.
  3. Number vs String → String to Number. BigInt vs String → String to BigInt.
  4. Boolean → Number, then recurse.
  5. Object vs primitive → ToPrimitive(object) with the default hint, then recurse. For ordinary objects that's valueOf then toString; Date is the built-in that overrides the default hint to string.

Rule 5 is where the surprises live, not the "leniency".

ExpressionResultWhy
0 == ""true"" → 0
0 == "0"true"0" → 0
"" == "0"falsesame type, no conversion
" \t\n" == 0truewhitespace → 0
false == "0"truefalse → 0, then "0" → 0
false == "false"false"false" → NaN
[] == 0true[] → "" → 0
[0] == 0true[0] → "0" → 0
[0] == ""false"0" vs ""
new Date(0) == 0falseDate → string, then NaN
null == 0falsenull equals only undefined
NaN == NaNfalse

Read the first three rows together: 0 == "", 0 == "0", but "" != "0". == is not transitive, so it is not an equivalence relation: it cannot back a sort comparator, a dedup pass, a Set/Map key, or a memo key. === is transitive and reflexive except for NaN.

Failure modes and how I'd detect them. The realistic one is a boundary that admits strings: if (count == 0) is true for "0", "", " ", and false. It survives review because the happy path sends numbers. Detection: fuzz the boundary across the full type set (number, numeric string, whitespace string, empty string, boolean, null, undefined, array) and assert which branch is taken; turn on ESLint eqeqeq with "smart" so == null stays legal and every other == is an error; TypeScript's 2367 catches "0" == 0 but not when the value is any out of JSON.parse, which is precisely the boundary case. In browsers, document.all is the one value that breaks the x == null idiom, it compares == null and typeof it is "undefined", so if the code touches the DOM, that idiom isn't a guarantee either.

JavaScript
const raw = process.env.RETRY_LIMIT;            // string | undefined
const retries = raw === undefined ? 3 : Number(raw);
if (!Number.isInteger(retries) || retries < 0) throw new RangeError(`bad RETRY_LIMIT: ${raw}`);

Note the trap that survives the rewrite: Number("") and Number(" ") are both 0, so an empty env var silently becomes zero retries. Explicit conversion moves the decision into code you can read and test; it doesn't remove the need to validate.

What I'd say in the review. Keep == null if you want it. Replace every other == with === and convert once at the boundary. If the design genuinely needs coercion, write it as a named function with a test per input type, so the assumption is visible instead of implicit in the operator.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach operator coercion and object-to-primitive conversion to an engineer who has only seen it as a rule of thumb.

Answer

The 90-second version

+ is the only arithmetic operator that looks at types. It runs ToPrimitive on both operands with hint "default"; if either result is a String it concatenates, otherwise it converts both to numeric and adds. Every other arithmetic operator (-, *, /, %, **) runs ToPrimitive with hint "number" and then ToNumber. So "3" + 4 is "34" and "3" - 4 is -1, and the difference is the hint, not the operator's strictness.

ToPrimitive, exactly

Given an object and a hint of "number", "string" or "default":

  1. If the object has Symbol.toPrimitive, call it with the hint string and use the result if it is a primitive.
  2. Otherwise, if the hint is "default", treat it as "number".
  3. Try valueOf(), then toString() for "number"; the reverse for "string". The first call that returns a primitive wins.
  4. If neither returns a primitive, throw TypeError.

Which hint each construct passes:

ConstructHint
binary +, == against a primitive"default"
-, *, /, %, **, unary +, <, >"number"
template literal, String(x)"string"

Date is the one built-in that overrides Symbol.toPrimitive to map "default" to "string", which is why new Date() + 1 concatenates but +new Date() is a number.

Trace

JavaScript
const o = {
  [Symbol.toPrimitive](hint) { return hint === "number" ? 1 : "one"; },
};
o + 1;    // "one1"  — hint "default", not "number", so "one"; then string concat
+o;       // 1       — hint "number"
`${o}`;   // "one"   — hint "string"

Drop Symbol.toPrimitive and give the same object valueOf returning 42 and toString returning "str": o + 1 is 43 (valueOf first) but `${o}` is "str" (toString first).

Arrays inherit a valueOf that returns the array itself, so they fall through to toString, which is join(","). That makes [] + {} evaluate as "" + "[object Object]" → "[object Object]", and [1, 2] + [3] as "1,2" + "3" → "1,23".

Failure modes

  • Form and query-string values are strings. total + qty concatenates into a longer string instead of throwing, so it survives a happy-path test. Catch it with a type assertion or schema validator at the boundary, not by reading the code.
  • [10, 9, 1].sort() sorts as strings → [1, 10, 9]. Pass a comparator.
  • Number(""), Number(" ") and Number(null) are all 0; Number(undefined) is NaN. A missing field silently becomes zero.
  • parseInt("12px") is 12: it stops at the first non-digit. Number("12px") is NaN.
  • +Symbol() and `${Symbol()}` throw TypeError; String(sym) does not.

Trade-offs

Convert at the boundary with Number when the input must be a whole number and trailing garbage should fail loudly. Reach for parseInt(s, 10) only when you deliberately want to accept a numeric prefix ("12px", a CSS value) and never without the radix. Explicit conversion is the wrong call when the string is the value: an account number, a postcode, a phone number with a leading +. Converting those to a number drops leading zeros and loses precision past 2^53, and you convert back for display anyway. Keep them as strings and convert only at the arithmetic site.

Overriding valueOf or Symbol.toPrimitive on a domain object pays off only when the type has exactly one obvious primitive meaning and you accept that + will silently use it: a Duration in milliseconds, say. For Money, don't: price + tax and price + " USD" would both route through the same hook, and the second is a bug you cannot see at the call site. Use named methods (add, format) instead.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does the NaN and negative-zero cases matter, and where is it irrelevant?

Answer

Core answer. The distinction matters exactly where the operation is specified to preserve the sign bit or the NaN identity, and it is irrelevant wherever the operation routes through SameValueZero, string coercion, or JSON. NaN matters for indexOf vs includes, for Map/Set keys, for JSON.stringify, for the x !== x test, and for sort comparators. Negative zero matters for 1/x, Math.atan2, Math.sign, Object.is, and React's useState bailout; it is irrelevant for Map/Set keys, includes, indexOf, JSON.stringify, and String().

Where each one bites, and where it does not.

OperationNaN-0
===never equal to itselfequal to 0
Object.isequal to itselfdistinct from 0
Array#includes (SameValueZero)foundsame as 0
Array#indexOf (strict)-1same as 0
Map/Set key (SameValueZero)workscollides with 0
JSON.stringify"null""0"
String()"NaN""0"
1/xNaN-Infinity vs Infinity
Math.atan2(0, x)NaNπ vs 0
Math.signNaN-0 vs 0
Math.min(0, -0)NaN propagates-0
React useState bailout (Object.is)bails outre-renders

Failure modes. The NaN one that ships: Number("abc") → NaN, then if (x === NaN) never fires, so the invalid value flows into a sum and the total becomes NaN three functions later. Detect it with Number.isNaN(x) or x !== x; isNaN("abc") is true because it coerces first, so it is a coercion test, not a NaN test. The second: JSON.stringify({v: NaN}) → '{"v":null}', and null + 1 is 1, so a missing measurement silently becomes a number on the wire. The third: a sort comparator that returns NaN (e.g. a - b with a NaN operand) makes the order implementation-defined: filter NaN before sorting or assert the comparator returns a finite number.

The -0 one that ships: 1/x < 0 as a sign test flips for -0, and Math.atan2(0, -0) is π while Math.atan2(0, 0) is 0, so geometry code that ignores the sign of zero gets the wrong quadrant. Rounding manufactures it too: Math.round(-0.4) and Math.ceil(-0.5) both return -0. JSON.stringify(-0) is "0", so a signed zero does not survive a round-trip. React's useState compares with Object.is, so setState(0) then setState(-0) re-renders while setState(NaN) twice does not.

Where it is irrelevant. Map and Set use SameValueZero, so NaN is a usable key and -0 collides with 0; includes finds both; indexOf finds -0 but not NaN; String() and JSON.stringify collapse -0 to "0"; and === treats 0 and -0 as equal. If your code never inspects the sign bit and never compares against NaN, neither case changes a result.

The conditional. Reach for Object.is only where the -0 distinction or the NaN identity is load-bearing: React state, Map keys you control, sign-sensitive math. Everywhere else, Number.isNaN for the NaN test and === for the rest is the cheaper, clearer choice.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through strings as UTF-16 code units, including where engineers most often get it wrong.

Answer

A JavaScript string is an immutable sequence of UTF-16 code units. length counts units, not characters. Everything else is bookkeeping about which of four counts you actually want.

what you wanthow to get it"a😀e\u0301""👨👩👧👦"
UTF-16 code unitss.length511
code points[...s].length47
grapheme clustersIntl.Segmenter31
UTF-8 bytesnew TextEncoder().encode(s).length825

Anything outside the BMP (emoji, CJK extension blocks, musical symbols) is stored as a surrogate pair and costs two units. The bug that follows is treating length as "number of characters" and slicing on it.

JavaScript
const s = "a\u{1F600}e\u0301";          // 'a', U+1F600, 'e', U+0301
s.length;                                 // 5
[...s].length;                            // 4
s.slice(0, 2);                            // "a\uD83D" — 'a' plus a lone high surrogate
encodeURIComponent(s.slice(0, 2));        // throws URIError: URI malformed
new TextEncoder().encode(s.slice(0, 2));  // Uint8Array [0x61, 0xEF, 0xBF, 0xBD]

The lone surrogate is the interesting part. It sits in memory without complaint, and the moment it is serialized to UTF-8 (a fetch body, Buffer.from, a database driver) it becomes U+FFFD. The name is not shortened; it is corrupted, and the corruption happens downstream of the code that caused it.

Two more places the unit count leaks out:

JavaScript
/^.$/.test("😀");   // false — . matches one code unit, the string has two
/^.$/u.test("😀");  // true

"\u0065\u0301" === "\u00E9";                  // false — same grapheme, different code points
"\u0065\u0301".normalize("NFC") === "\u00E9"; // true

Failure modes worth naming in an interview:

  • Truncation. s.slice(0, 20) on a name with an emoji at the boundary yields a lone surrogate. Detect it by scanning stored text for U+FFFD and by putting astral input in fixtures; a happy-path test with ASCII never sees it.
  • Reversal. s.split("").reverse().join("") swaps the halves of every surrogate pair. [...s].reverse().join("") fixes pairs but still breaks combining marks and ZWJ sequences, so user-visible reversal needs the segmenter.
  • Regex without /u. . and character classes match single units, so ^.{1,10}$ accepts five emoji as ten units. Add /u (or /v for set notation).
  • Comparison. "é" from a macOS filename is NFD; from a web form it is usually NFC. ===, Set and Map keys treat them as different strings. Normalize at the input boundary, not at every comparison.
  • Limits. HTML maxlength and JS length count UTF-16 units; MySQL VARCHAR(20) in utf8mb4 counts code points; a 20-byte column counts bytes. The same input is three different numbers. Pick the one the product means and validate against it.
  • Sorting. < compares code units, so "Z" < "a" and astral characters sort after every BMP character. Use Intl.Collator or localeCompare for anything a user reads.

In practice: iterate with for...of or Array.from when the unit is a code point; use Intl.Segmenter with granularity: "grapheme" (Node 16+, current browser releases) when it is a grapheme; call normalize("NFC") once at the boundary where text enters the system; and measure storage with TextEncoder or Buffer.byteLength rather than length.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you reason about numbers as IEEE-754 doubles in a system you own?

Answer

Ask first what the numbers are. Money, identifiers, counters and measurements have different requirements, and the answer changes with them. The rule that covers all four: a double is exact for integers up to 2^53 − 1 and inexact for most decimal fractions, and every arithmetic result is rounded to the nearest representable double. So anything that must stay exact goes in an exact representation (integer minor units, BigInt, or a decimal library) and any computed double is treated as approximate.

Mechanism. A double is 64 bits: 1 sign, 11 exponent, 52 stored mantissa bits, giving 53 bits of precision. The value is ±1.mantissa × 2^(exponent−1023). Adjacent doubles are 2^(exponent−52) apart, so the gap at 1.0 is 2^−52 ≈ 2.22e−16 (Number.EPSILON) and it doubles at every power of two. 0.1 has no finite binary expansion; the nearest double is 0.1000000000000000055511151231257827. IEEE 754's default rounding is round-to-nearest, ties-to-even, applied after every operation.

JavaScript
0.1 + 0.2;                    // 0.30000000000000004
0.1 + 0.7;                    // 0.7999999999999999
0.1 + 0.2 + 0.3;              // 0.6000000000000001
0.1 + 0.2 === 0.3;            // false
Number.MAX_SAFE_INTEGER;      // 9007199254740991 = 2**53 - 1
9007199254740992 === 9007199254740993;  // true: both round to 2**53
Number.isSafeInteger(9007199254740993); // false
JSON.parse('{"id":9007199254740993}').id; // 9007199254740992
[10, 9, 100].sort();          // [10, 100, 9] — default sort is lexicographic

The first three lines are one mechanism seen three times: each sum is rounded, and the error lands in the last digit. The 2^53 pair shows the other edge: above 2^53 the spacing is 2, so two distinct integers collapse to one double, and JSON.parse does that silently to any ID that arrives as a bare number.

Failure modes and how you catch them.

  • Money drift: summing cents as doubles accumulates error, and a ledger drifts by fractions of a cent until it reconciles wrong. Hold money as integer minor units (2^53 − 1 cents is about $90 trillion, plenty) or a decimal type, and assert Number.isSafeInteger on every amount at the boundary.
  • Identifier collision: an ID above 2^53 from an API or JSON body is already wrong by the time you see it. Parse IDs as strings, and log the string form so a mismatch is visible.
  • Equality: === on computed floats fails for values a human calls equal. Compare with a tolerance chosen from the domain (1e-9 for sensor readings, say), or compare exact integers after scaling.
  • Sort order: Array.prototype.sort with no comparator sorts by string, so [10, 9, 100] becomes [10, 100, 9]. Always pass (a, b) => a - b for numbers.
  • Accumulation: long sums of small values lose low-order bits; Kahan summation or sorting by magnitude first recovers most of it.

Trade-offs. BigInt is exact and unbounded but slower, has no Math methods, and throws on mixed Number/BigInt arithmetic. A decimal library is exact in base 10 and costs a dependency and speed. Integer minor units are the fastest and the usual choice for money, at the price of fixing the scale and currency up front. Tolerance comparison is cheapest but only as good as the tolerance you pick: Number.EPSILON is the wrong default, since it is the gap at 1.0, not at your magnitude.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How do var, let, and const differ in terms of scoping, redeclaration, and the temporal dead zone (TDZ)?

Answer

var is function-scoped, hoists to undefined, and can be redeclared. let and const are block-scoped, sit in a temporal dead zone (TDZ) until their declaration executes, and cannot be redeclared in the same scope. const additionally forbids reassignment. The deciding rule in practice: default to const, switch to let only when the binding must be reassigned, and treat var as legacy except when you specifically need function-scoped hoisting.

Propertyvarletconst
ScopeEnclosing function or global execution contextEnclosing block ({ ... })Enclosing block ({ ... })
Re-declarationAllowed in same scopeEarly SyntaxErrorEarly SyntaxError
Initialization on entryImmediately undefinedUninitialized until evaluationUninitialized until evaluation
Temporal Dead ZoneNo (undefined before line)Yes (ReferenceError on access)Yes (ReferenceError on access)
Re-assignmentAllowedAllowedRuntime TypeError
Global object attachmentAttaches as global property (window.x) in a classic scriptDoes not attachDoes not attach

TDZ mechanics

The binding is created when the execution context is instantiated, but let/const bindings start uninitialized. Accessing one before its declaration statement runs throws ReferenceError. typeof is not a safe escape hatch here: typeof undeclaredVar yields "undefined", but typeof letVarBeforeDeclaration throws.

JavaScript
function demonstrateBindings() {
  console.log(hoistedVar); // undefined
  var hoistedVar = 10;

  try {
    console.log(blockLet); // ReferenceError: Cannot access 'blockLet' before initialization
  } catch (err) {
    console.log(err.name); // 'ReferenceError'
  }

  let blockLet = 20; // TDZ ends here
  console.log(blockLet); // 20
}

Per-iteration loop bindings

var shares one mutable binding across all iterations; for (let ...) creates a fresh binding per iteration, which is the idiomatic fix for the closure-capture bug:

JavaScript
const varCallbacks = [];
for (var i = 0; i < 3; i++) varCallbacks.push(() => i);
console.log(varCallbacks.map(fn => fn())); // [3, 3, 3]

const letCallbacks = [];
for (let j = 0; j < 3; j++) letCallbacks.push(() => j);
console.log(letCallbacks.map(fn => fn())); // [0, 1, 2]

Choosing between them

  • const by default. It makes the binding's lifetime explicit and prevents accidental reassignment. ESLint's prefer-const rule enforces this. Use it for every binding you do not reassign, including objects and arrays you mutate in place.
  • let when the binding must change. Loop counters, accumulators, and values assigned in a branch. Prefer let over var in loops so each iteration captures its own value.
  • var only for legacy or deliberate function-scoping. A case where var is still the right tool: you want a binding to escape a block, e.g. a try block that assigns a value consumed after the block. Otherwise var's silent redeclaration and global-object attachment are footguns.

Failure modes

  • Redeclaration is an early error. let x = 1; let x = 2; fails at parse time with SyntaxError, so the whole script or module fails to load. var x = 1; var x = 2; silently overwrites, which can mask a bug.
  • TDZ is a runtime error. It only fires if the access actually executes, so a branch that never runs hides the bug until production.
  • const is not deep immutability. const obj = {}; obj.a = 1; is legal. Object.freeze(obj) blocks top-level mutation but is shallow; nested objects stay mutable.
  • Global leakage. In a classic script, top-level var x creates globalThis.x and can collide with existing window properties. Top-level let/const do not. In an ES module, top-level var is module-scoped, not global.

Performance is not a deciding factor: V8 and other modern engines optimize TDZ checks and per-iteration bindings to negligible cost in typical code.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How does hoisting differ between function declarations, function expressions, and variable declarations during the creation phase of an execution context?

Answer

During the creation phase of an execution context, the engine instantiates environment record bindings before executing any code. The difference between declarations lies in when their bindings are initialized and what value they receive during that phase.

Function declarations are hoisted in full: the identifier is bound in the environment record and immediately initialized with the complete function object. They can be invoked safely anywhere in their containing scope prior to the line of declaration.

Variable declarations behave differently depending on the declaration keyword:

  • var declarations create an identifier binding initialized immediately to undefined. Attempting to read or invoke it before its assignment statement yields undefined or throws a TypeError: <name> is not a function.
  • let and const declarations register an identifier binding, but leave it completely uninitialized. Accessing it prior to the declaration line triggers a ReferenceError via the Temporal Dead Zone (TDZ).

Function expressions are not declared as functions; they are expressions whose assignment occurs at runtime during the execution phase. The variable holding the expression follows the hoisting rules of its variable keyword (var, let, or const), while the function object itself is only instantiated when execution evaluates the assignment expression.

JavaScript
// Creation Phase:
// 1. fnDecl is bound and instantiated -> function fnDecl() { return "ok"; }
// 2. varExpr is bound and initialized -> undefined
// 3. constExpr is bound but left UNINITIALIZED

fnDecl();    // "ok"
varExpr();   // TypeError: varExpr is not a function
constExpr(); // ReferenceError: Cannot access 'constExpr' before initialization

function fnDecl() { return "ok"; }
var varExpr = function() { return "var"; };
const constExpr = () => "const";

A secondary distinction occurs with named function expressions: var f = function bar() {};. The identifier bar is not added to the enclosing scope's environment record during the creation phase at all. Instead, bar is bound solely inside the function instance's own internal environment record for self-recursion.

The most common production failure is treating a var-assigned function expression or a conditionally defined function declaration as safe to call pre-definition, turning compile-time safety assumptions into runtime TypeError crashes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How do closures capture variables by reference rather than by value, and how does this affect loops containing asynchronous callbacks?

Answer

Core answer. A closure does not capture values. It captures the environment record, the scope object, in which the function was created, and resolves identifiers against that record when it is called. Reassign the binding after the closure is created and the closure sees the new value. That is late binding, not a snapshot.

Mechanism. When a function object is created, the spec gives it a [[Environment]] slot pointing at the running execution context's LexicalEnvironment. Calling the function pushes a new environment whose outer pointer is that captured record. An identifier like i inside the closure is resolved by walking the chain at call time; no copy of i is stored on the closure. "Capture by reference" is loose phrasing: the closure holds a reference to the binding, not to a memory cell in the C++ sense.

The loop. var is function-scoped and hoisted, so for (var i = 0; ...) creates exactly one binding for the entire loop. Every callback scheduled in the body closes over that one binding. The event loop runs the synchronous loop to completion before draining any queue, so by the time a callback fires, i already holds its exit value.

JavaScript
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log('t', i), 0);
  Promise.resolve().then(() => console.log('p', i));
}
// p 3, p 3, p 3, t 3, t 3, t 3

Trace: the script body is one macrotask. It schedules three timers and three microtasks, then finishes with i === 3. The microtask queue drains before the next macrotask, so all three promise callbacks run first, then the three timers. All six read the same binding.

Swap var for let and the spec's CreatePerIterationEnvironment runs before each iteration body: the current value is copied into a fresh environment record, and the body's closures capture that record.

JavaScript
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log('t', i), 0);
  Promise.resolve().then(() => console.log('p', i));
}
// p 0, p 1, p 2, t 0, t 1, t 2
MechanismBinding scopeBindings createdAsync result
var iEnclosing function / global1Every callback logs the exit value N
let iPer-iteration block1 loop-head + 1 per iterationCallback for step k logs k
IIFE (k => ...)(i)New function activation1 parameter per callCallback for step k logs k
arr.forEach((x) => ...)Callback parameter1 per invocationCallback for element k logs element k

Fixes. let/const in the loop header is the idiomatic one. The IIFE still appears in older code and in transpiled output: for (var k = 0; k < 3; k++) { ((captured) => { setTimeout(() => console.log(captured), 0); })(k); }. The argument is evaluated per call, so each activation gets its own parameter binding. forEach, for...of with let, and map are already safe because each callback invocation gets a fresh parameter binding.

Failure modes and nuances.

  1. Mutation after dispatch. The bug is not limited to counters. A closure over a mutable object (state.current, a shared config) reads whatever the object holds when it runs, so any code between scheduling and firing can change the result. Detect it by logging the value at schedule time and at fire time.
  2. await inside the loop changes the picture. for (var i = 0; i < 3; i++) { await sleep(10); console.log(i); } prints 0, 1, 2. The loop suspends at the await, so each read happens before the next increment. The shared-binding bug needs fire-and-forget callbacks that outlive the loop, not awaited ones.
  3. Retention. At the spec level the closure keeps its environment record alive, so in principle every binding in that record survives. V8's context allocation analysis only moves variables actually referenced by an inner function into the heap-allocated Context; unreferenced siblings stay on the stack frame and are collected when it exits. "One closure pins the whole scope" is a spec-level simplification, not what current engines do: don't repeat it as a V8 fact.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How does closures and retained memory change if the workload grows by two orders of magnitude?

Answer

The retention mechanism doesn't change at 100x: a closure still keeps its captured bindings alive as long as the closure itself is reachable. What changes is which term dominates the arithmetic. Retained heap ≈ (bytes in each closure's retained set) × (number of live closures). At small scale both factors are small and the product is noise. At 100x, if either factor is unbounded, the product crosses the container's memory limit and the failure moves from a slow drift you notice next quarter to the first load test OOMing.

Worked example. A handler captures a 1 KB buffer and is stored in a module-level Map that never deletes:

JavaScript
// Node 20.x
const handlers = new Map(); // module scope, never cleared

function subscribe(id, socket) {
  const buf = Buffer.alloc(1024);                       // 1 KB captured
  const onData = (chunk) => buf.set(chunk.subarray(0, buf.length));
  socket.on('data', onData);
  socket.on('close', () => socket.off('data', onData)); // listener removed...
  handlers.set(id, onData);                             // ...but the Map still
}                                                       // holds onData, so buf
                                                        // stays reachable forever

Trace it: subscribe allocates buf, builds onData closing over it, registers the listener, and stores onData in handlers. When the socket closes, socket.off removes the listener from the socket, but handlers still references onData, so onData is reachable, so buf is reachable. The 1 KB is never freed.

At 10 rps that is 10 KB/s retained = 864 MB/day. On a 512 MB container, ~14 hours to OOM: it survives a test run and looks like a slow leak. At 1000 rps (100x) it is 1 MB/s = 86.4 GB/day, and the same container dies in ~8.5 minutes. Same code, same leak, 100x the rate. The bug was always there; scale is what makes it fatal.

What else shifts. GC generation behavior. At 10 rps the leaked bytes are a trickle into the old generation; minor GCs reclaim almost everything and the leak never shows in pause times. At 1000 rps the allocation rate is 100x, so minor GCs run far more often, and the surviving set, the leak, grows 100x faster. V8's mark-compact pause is roughly proportional to the live set, so pause times grow with the leak, not just with throughput. The symptom changes from "memory grows" to "p99 climbs, then the process dies." Diagnostic cost changes too: a heap snapshot at 100x live set is 100x larger and takes proportionally longer to capture and diff, so the tool that worked at 10 rps is now itself a stop-the-world event.

Alternatives and when to pick them.

  • Manual unsubscribe. Correct, but the number of sites that must get it right grows with the codebase, and at 100x request rate the absolute number of leaks per hour grows 100x even if the per-site error rate is constant.
  • WeakRef + FinalizationRegistry. Lets the GC reclaim the buffer if nothing else holds it. Finalizer callbacks are not guaranteed to run and not prompt, so this is a safety net, not a correctness mechanism: never use it to close a resource.
  • Bounded structures. An LRU cache with a max entry count, or a fixed connection pool, turns unbounded growth into a fixed ceiling. Cost: eviction policy and cache misses. Right answer when the retained set is naturally bounded.
  • Scope-owned lifetime. AbortController/AbortSignal in Node, context in Go: cleanup is tied to scope exit rather than a manual call, so you can't forget it. Cost: restructuring code around scopes.

Deciding criterion: is the retained set bounded by design? If yes (pool, cache with a max), 100x is a capacity question: size the pool and move on. If no (one entry per request, per connection, per user), 100x is a correctness question and the leak rate is now the dominant term.

Failure modes and detection. Listener leak: addEventListener with no matching removeEventListener, so the closure keeps its captures alive. Timer leak: setInterval never cleared. Unbounded cache: a Map that only ever grows. Detect by taking a heap snapshot at t=0 and again after N identical user journeys, then diffing retained size by constructor: a growing count of the same closure type retaining the same buffer is the signature. RSS slope at a fixed request rate gives you the leak in bytes/request, which is the number that tells you whether 100x is survivable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How is the value of 'this' determined at execution time in standard JavaScript functions, and how does it differ across strict and non-strict modes?

Answer

this is bound at call time, not at declaration. The engine derives it from the call-site expression and then adjusts it according to the execution mode: strict mode passes the caller's value through untouched, sloppy mode substitutes globalThis for null/undefined and boxes primitives.

The runtime mechanism

When obj.method() is evaluated, the member expression produces an internal Reference Record: a base (obj), a referenced name ('method'), and a strict flag. The call operator () then does one of two things:

  1. If the operand is still a Reference whose base is an object, that base becomes the thisValue.
  2. If the reference was dereferenced first (const fn = obj.method, (0, obj.method)(), or passing the method as a callback) GetValue() collapses it to a bare function object and the base is discarded. The call is standalone, with an undefined base.

Strict vs. non-strict

InvocationStrict ("use strict")Sloppy
fn()undefinedglobalThis
"str".fn()"str"new String("str")
fn.call(null)nullglobalThis
fn.call(undefined)undefinedglobalThis
new fn()new objectnew object
fn.bind(x)()xx

new and bind override the table: a constructor call always sets this to the freshly created object, and a bound function ignores the call-site base entirely.

Trace

JavaScript
function showThis() { return this; }
function showThisStrict() { "use strict"; return this; }
const host = { showThis, showThisStrict };

host.showThis();        // host
host.showThisStrict();  // host

const detached = host.showThisStrict;
detached();             // undefined

(0, host.showThisStrict)(); // undefined
(0, host.showThis)();       // globalThis

showThis.call(42);       // [Number: 42]
showThisStrict.call(42); // 42

Choosing between them

The decision is usually already made for you: ES modules, class bodies, and anything defined inside them are strict regardless of a "use strict" directive. The sloppy column applies to legacy non-module scripts and CommonJS files that never opt in. For new code, prefer strict.

What sloppy coercion costs you:

  • Global substitution hides typos. A stray this.cache = ... in a callback writes to the realm-wide globalThis, so one library's leak becomes another's state. Strict mode turns the same mistake into a TypeError at the call site, which is the point.
  • Boxing breaks identity. In sloppy mode fn.call("x") gives a fresh String wrapper, so this === "x" is false and typeof this === "object". Any comparison against a primitive silently never matches. Strict mode keeps this === "x".
  • Boxing allocates per call. Each primitive receiver produces a new wrapper, so caching on this across calls does not accumulate where you expect.

What strict costs you:

  • Callbacks invoked as fn() receive undefined, so a library that calls your method without a receiver throws where sloppy code would have limped along against globalThis. Migrating means auditing bare fn() calls and .call(null) sites.
  • fn.call(null) now passes null; code that used null to mean "use the global" must say globalThis explicitly.

Failure mode

Passing a method reference into a higher-order function (setTimeout(obj.fetchData, 100), array.map(obj.transformer)) hands the engine a bare function with no base. Strict mode throws TypeError: Cannot read properties of undefined on the first this.property access; sloppy mode silently reads or writes globalThis. The fix is the same in both modes: obj.fetchData.bind(obj) or an arrow wrapper. Relying on substitution to paper over a missing receiver is the reason the strict default exists.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

In what scenarios should arrow functions be avoided due to their lexical binding of this?

Answer

Arrow functions capture this from the scope where they are defined. They ignore the receiver supplied by the call site: call, apply, bind, new, and DOM event dispatch cannot change it. Avoid them when the function must use the caller's this.

Checked against Node 20.11 / ES2022; DOM behavior per the WHATWG DOM Standard.

Object literal methods

An arrow method captures the enclosing scope's this, not the object it is attached to.

JavaScript
function makeCounter() {
  return {
    count: 0,
    incBad: () => { this.count++; },
    incGood() { this.count++; }
  };
}

const receiver = { count: 100 };
const counter = makeCounter.call(receiver);

counter.incBad();
console.log(counter.count, receiver.count); // 0 101
counter.incGood();
console.log(counter.count, receiver.count); // 1 101

makeCounter.call(receiver) sets this to receiver inside makeCounter. incBad captures that receiver, so counter.incBad() increments receiver.count to 101 and leaves counter.count at 0. incGood is a method shorthand, so counter.incGood() gets counter as this and increments counter.count to 1.

Prototype and class methods

call, apply, and bind cannot override an arrow function's lexical this. That breaks prototype methods that expect the invoking instance.

JavaScript
function User(name) { this.name = name; }

const outer = { name: 'outer' };
function install() {
  User.prototype.greetBad = () => `Hello, ${this.name}`;
}
install.call(outer);

const alice = new User('Alice');
console.log(alice.greetBad()); // 'Hello, outer'
console.log(alice.greetBad.call({ name: 'Bob' })); // 'Hello, outer'

The arrow captured outer when install ran. Calling it on alice or with .call({ name: 'Bob' }) does not rebind it. The correct prototype method is a normal function:

JavaScript
User.prototype.greetGood = function() { return `Hello, ${this.name}`; };
console.log(alice.greetGood()); // 'Hello, Alice'

DOM event handlers that use this

The DOM Standard sets this to event.currentTarget for a non-arrow listener. An arrow listener ignores that.

JavaScript
button.addEventListener('click', () => {
  this.classList.toggle('active');
});

In an ES module, top-level this is undefined, so the handler throws TypeError: Cannot read properties of undefined (reading 'classList'). In a classic script, this is window, so it throws TypeError: Cannot read properties of undefined (reading 'toggle') because window.classList is undefined. Use function () { this.classList.toggle('active'); } or (event) => event.currentTarget.classList.toggle('active').

Constructors

Arrow functions have no own this and no [[Construct]] internal method. new (() => {}) throws a TypeError; use a normal function or class.

Callbacks with a thisArg

Array methods such as map, filter, and forEach accept a thisArg. Arrow callbacks ignore it. If the callback needs that receiver, pass a normal function.

ScenarioWhy the arrow failsUse instead
Object literal methodthis is the enclosing scope, not the objectmethod shorthand inc() {}
Prototype/class methodcall/apply cannot rebind; instance receiver ignoredfunction or class method
DOM event handler using thisthis is not event.currentTargetfunction or event.currentTarget
Constructorno own this, no [[Construct]]; new throwsfunction or class
Callback with thisArgarrow ignores the supplied thisArgnormal function

The inverse is also worth stating: inside a method, setTimeout(() => this.tick(), 0) is usually correct because you want the method's this, not the timer's.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-15

How would you explain call, apply, and bind without using the usual slogan?

Answer

The 90-second answer

Every call carries a this value, decided by how the call is written: obj.m() sets it to obj, a bare m() sets it to undefined in strict code or globalThis in sloppy code. call, apply and bind are the three ways to override that decision from the call site.

call and apply invoke the target now, with the receiver you pass as the first argument. They differ only in argument shape: call takes them spread, apply takes one array-like. bind invokes nothing; it returns a new function object carrying three internal slots (target, bound this, bound arguments) and every later call to that object routes through them.

invokes nowargumentsthisreturns
fn.call(t, a, b)yesspreadtfn's result
fn.apply(t, [a, b])yesone array-liketfn's result
fn.bind(t, a)nospread, prependedt, fixednew function

The "fixed" in that last cell is the part worth being precise about, because it has two exceptions.

JavaScript
function who(greeting) { return `${greeting} ${this.name}`; }

who.call({ name: "a" }, "hi");          // "hi a"
who.apply({ name: "a" }, ["hi"]);       // "hi a"

const bound = who.bind({ name: "b" }, "hey");
bound();                                // "hey b"
bound.call({ name: "c" });              // "hey b" — bound this wins
bound.bind({ name: "d" })();            // "hey b" — a second bind cannot rebind

function Point(x) { this.x = x; }
const Bound = Point.bind({ x: 99 }, 1);
new Bound().x;                          // 1 — bound this ignored under new

Trace the third line: bound has bound this {name:"b"} and bound args ["hey"]. bound.call({name:"c"}) passes {name:"c"} as the thisArgument, but the bound function discards it and calls who with {name:"b"} and ["hey"]. Same for the fourth: bound.bind({name:"d"}) creates a new bound function whose target is bound; invoking it calls bound with {name:"d"}, which bound again discards. The first bind wins.

The new case is the exception people miss. When a bound function is constructed, the bound this is thrown away and the target runs as a constructor against a fresh object. So bind fixes the receiver for ordinary calls only.

Two more edges. apply accepts any array-like, not just arrays, so Math.max.apply(null, {length: 2, 0: 5, 1: 9}) returns 9 while Math.max(...{length: 2, 0: 5, 1: 9}) throws, because spread needs an iterable. And arrow functions have no own this, so all three are no-ops on them: the receiver comes from the enclosing scope.

Where it bites

JavaScript
el.addEventListener("click", handler.bind(this));
el.removeEventListener("click", handler.bind(this)); // no-op

Each bind allocates a fresh function object, so the second one is not the first one and removal silently does nothing. The same allocation happens if you bind inside a render path or a loop, which breaks any downstream === check on the handler. Bind once at construction and store the reference. The returned function also reports name as "bound who" and length as the target's arity minus the bound arguments: bound.length above is 0.

Use call/apply for one-off borrowing: Array.prototype.slice.call(arguments) predates spread. Reflect.apply(fn, thisArg, args) is the same operation with the function passed as an argument, so it still works when fn has its own apply property. Use bind when you need a stable, pre-configured function to hand to something else.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of the prototype chain?

Answer

The injection: patch a shared prototype at runtime and ask for the blast radius.

In a test build, add a method to Object.prototype (or to a shared base prototype the app uses) and ask the team which objects change behaviour. The method itself is irrelevant; the answer you are listening for is "every object whose chain reaches that prototype, including ones created in modules I have never opened, and for...in now yields the new key."

JavaScript
Object.prototype.describe = function () { return "x"; };  // enumerable own prop on Object.prototype

const user = { id: 7 };
for (const k in user) console.log(k);   // id, describe
Object.keys(user);                       // ["id"]
JSON.stringify(user);                    // '{"id":7}'

Trace: the assignment creates an enumerable, writable property on Object.prototype. for...in walks the chain and includes enumerable inherited keys, so describe appears. Object.keys and JSON.stringify only look at own enumerable properties, so they do not. A team that predicts only the first line, or only the last two, has half the model.

Second injection: assignment to an accessor-only inherited property.

JavaScript
const proto = { get greet() { return "hi"; } };
const a = Object.create(proto);
a.greet = "hello";          // sloppy mode: silently ignored
a.greet;                    // "hi"
Object.hasOwn(a, "greet");  // false

This separates "assignment shadows the prototype" from the real rule: assignment creates an own property only if the inherited property is a writable data property. A getter with no setter blocks it: silently in sloppy mode, TypeError in strict mode. Teams that memorised "assignment shadows" get this one wrong.

Third injection: Object.create(null) and a call to an inherited method.

JavaScript
const dict = Object.create(null);
dict.hasOwnProperty("x");   // TypeError: dict.hasOwnProperty is not a function

Tests whether they know the chain terminates at null and that hasOwnProperty is inherited, not built in.

InjectionWrong answer it catches
Object.prototype.describe = ..."Only the patched class changes"
assign to getter-only inherited prop"Assignment always shadows"
Object.create(null).hasOwnProperty(...)"Every object has hasOwnProperty"

Why these survive casual testing. The patch is invisible until something enumerates or calls the new name, so a unit test that only checks the patched class passes. The getter-only assignment fails silently in sloppy mode, so a test that does not assert on the value passes. The null-prototype call only throws on the code path that reaches it.

When not to use this. Do not run the prototype patch against a shared staging environment: it leaks into every request in the process. Run it in a throwaway process or a test build with the patch scoped to a single module load. And if the codebase already uses Object.create(null) for dictionaries and Object.hasOwn for own-ness checks, the first injection tests nothing they have not already internalised; pick the accessor one instead.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Walk me through property descriptors and enumerability: what Object.getOwnPropertyDescriptor returns, how Object.defineProperty uses it, and how enumerable decides what for...in, Object.keys, spread and JSON.stringify see.

Answer

The 90-second version. A property is a name plus a descriptor. Object.getOwnPropertyDescriptor(obj, key) returns that descriptor for an own property, and undefined if the property is inherited or absent. A data descriptor has value, writable, enumerable, configurable; an accessor descriptor has get, set, enumerable, configurable. Never both shapes at once. Object.defineProperty writes that descriptor, and the trap is the defaults: a property created this way is non-writable, non-enumerable and non-configurable unless you say otherwise. enumerable is the flag that decides whether the property is visible to enumeration, copying and serialization.

js const o = {}; Object.defineProperty(o, "id", { value: 7 }); Object.getOwnPropertyDescriptor(o, "id"); // { value: 7, writable: false, enumerable: false, configurable: false }

o.id = 8; // sloppy mode: silently ignored o.id; // 7 Object.keys(o); // [] JSON.stringify(o); // '{}' for (const k in o) console.log(k); // nothing

Compare const p = { id: 7 }: a literal sets writable, enumerable and configurable all to true. Same value, different descriptor, different behaviour under every operation below.

OperationOwnInheritedNon-enumerableSymbol keys
for...inyesyesnono
Object.keysyesnonono
Object.getOwnPropertyNamesyesnoyesno
Object.assign / {...o}yesnonoyes
JSON.stringifyyesnonono

Spread and Object.assign copy own enumerable string and symbol keys; JSON.stringify skips symbol keys and drops values that are undefined or functions. That asymmetry is where real bugs live: a class instance whose fields were defined non-enumerable serializes to {} with no error.

Accessors. get/set replace value/writable. A getter in an object literal is enumerable by default; a method declared in a class body is non-enumerable on the prototype, which is why for...in over an instance never yields toString or your own methods. configurable: false means you cannot delete the property, change enumerable or configurable, or flip between data and accessor shape; writable may go true to false but not back.

Own versus inherited. Descriptors are own-only. Object.getOwnPropertyDescriptor([], "length") gives { value: 0, writable: true, enumerable: false, configurable: false }: that is why for...in over an array yields indices and not length. Array.prototype.map is non-enumerable, so it stays out of for...in; assign Array.prototype.foo = 1 and every array now yields foo, because for...in walks the chain and includes inherited enumerable keys. That is the observable symptom of prototype pollution, and the cheap detector is diffing for...in against Object.keys.

Failure modes. In sloppy mode, writing to a non-writable property or deleting a non-configurable one fails silently; in strict mode and ES modules it throws TypeError, so the same code behaves differently depending on file type. A non-enumerable field vanishes from JSON.stringify and from spread, so a round-trip through a queue loses it. Object.defineProperty is for library and framework internals: memoized getters, frozen config, polyfills. Application code should use literals and classes; reach for descriptors when you deliberately want a property hidden from enumeration or read-only.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

How should on-call treat an alert that names classes over prototypes as the cause?

Answer

The first two minutes

Treat "classes over prototypes" as the alert author's guess about a cause, not as a finding. What paged you is a number (heap growth, GC pause p99, listener count) and the attribution came from whoever wrote the rule or annotated the runbook. Confirm the number, then confirm something user-visible sits behind it. No symptom means no incident: the alert becomes a ticket, and the rule gets rewritten after the shift, not during it.

The attribution is wrong as a mechanism. A class declaration is a constructor plus a prototype object. class Row { size() {} } puts size on Row.prototype, the same slot Row.prototype.size = function () {} uses; the keyword allocates nothing per instance. Closures allocate: an arrow function assigned to a field, or .bind(this) in the constructor, creates one function object per instance, each closing over that instance. That is a real cost worth paging on at scale, but the variable is per-instance closures, not class syntax, and which one it is decides whether you wake the author of the last commit or keep looking.

JavaScript
// v1
function Row(el) { this.el = el; }
Row.prototype.onClick = function () { this.el.classList.add('selected'); };

// v2 — the commit the alert blames
class Row {
  #el;
  constructor(el) {
    this.#el = el;
    this.onClick = () => this.#el.classList.add('selected');
  }
}

const a = new Row(d1), b = new Row(d2);

v1: both rows resolve onClick through Row.prototype, so a.onClick === b.onClick is true, Object.getOwnPropertyNames(a) is ['el'], and Object.getOwnPropertyNames(Row.prototype) is ['constructor', 'onClick'].

v2: each constructor call evaluates the arrow, so every row gets a fresh function closing over that call's this. a.onClick === b.onClick is false, Object.getOwnPropertyNames(a) is ['onClick'] (the #el slot is a private name, not a property), and Object.getOwnPropertyNames(Row.prototype) is ['constructor'] because the handler never lived there. A private method, #onClick(){}, is installed once on the class's private environment and does not add per-instance functions; only the arrow field does.

Bound the cause before acting on it

Read the instance count off a heap snapshot, not off the alert. 50,000 live rows at roughly 150 bytes per arrow function plus the context it retains lands near 7.5 MB: 50,000 * 150 = 7,500,000 bytes, and 150 is an order-of-magnitude figure you should replace with your own from the snapshot. That explains a 10-20 MB drift across a deploy. It does not explain a 1.5 GB climb; when the graph goes vertical the closures are a rounding error and the real retainer is elsewhere, most often rows held alive by listeners nobody removed.

Which handler form to keep

The deciding criterion is instance count times lifetime, not the syntax that produced the closure.

Handler formAllocated per instanceRight whenFails when
Method on the class, bound inline at the registration site: el.addEventListener('click', () => this.onClick())one closure per registrationyou register once per instance and never remove ityou need removeEventListener. That arrow has no other reference, so the listener leaks
Arrow field: onClick = () => ...one closure per instancecounts are small, or you must remove by identity laterinstance counts run to hundreds of thousands and rows are long-lived
Prototype method plus this.onClick = this.onClick.bind(this) in the constructorone bound function per instanceyou need a stable reference for removalsame memory profile as the arrow field, with a worse stack trace
One delegated listener on the container, event.target.closest('[data-row]')nothing per rowlong lists with add/remove churnper-row state or stopPropagation semantics drive the behaviour

Detectors

  • Rows retained by a live listener: queryObjects(Row) in the Chrome DevTools console with Row in scope, plus a snapshot filtered to Detached nodes. A count that only grows names the bug. In Node, the same check is a heap snapshot through --inspect.
  • Listener pile-up: getEventListeners(container) in the console. It climbing after each render is the same retention with the row still attached.
  • Allocation-rate pressure: converting a shared method to an arrow field turns once-per-class work into once-per-row work, which shows up as GC pause rather than retained size. Allocation sampling in the Performance panel separates it from a genuine leak.

Mitigation

Revert the commit if the page is real: the class version stays, and either the binding moves to the single registration site or the listener moves to the container as a delegated handler. Rewrite the alert afterwards to fire on listener count or retained size, so the next responder starts from the measurement instead of the attribution.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does arrays as objects with a length force that a junior answer usually skips?

Answer

The 90-second answer

The trade-off is that length is a writable bound, not a count. An array is an ordinary object with a special length property the engine keeps equal to the highest index plus one, not the number of elements present. That buys O(1) index writes and O(1) growth: a[a.length] = x never scans or reallocates. It costs the invariant a junior assumes, that length tells you how many elements there are. const a = []; a[3] = 1 gives length === 4 with one element. And because length is writable, a.length = 1 deletes the rest in place, irreversibly.

The second half is that "array is an object" is not free at runtime. Index access is a property access, and V8 only makes it fast by tracking an elements kind per array. Start packed and you stay fast; introduce a hole, a non-index property, or a mixed type and the array generalizes to a slower representation, and that transition is one-way.

Mechanism: elements kinds

KindHow you get thereCost
PACKED_SMI_ELEMENTS[1, 2, 3]fastest; unboxed small ints
PACKED_DOUBLE_ELEMENTS[1, 2, 3.5]boxed doubles
PACKED_ELEMENTS[1, 'a']tagged pointers
HOLEY_*a[3] = 1, delete a[0], new Array(3)hole check on every read
DICTIONARY_ELEMENTSa[100000] = 1 on a small array, or many deleteshash lookup, no fast path

Transitions only go down: PACKED_SMI → PACKED_DOUBLE → PACKED_ELEMENTS, and packed → holey at any level. You cannot go back.

Trace

JavaScript
const a = [1, 2, 3];        // PACKED_SMI_ELEMENTS
a[5] = 6;                   // HOLEY_SMI_ELEMENTS, length 6
a.length;                   // 6
a.map(x => x * 2);          // [2, 4, 6, <2 empty items>, 12], length 6
a.filter(x => true);        // [1, 2, 3, 6]  — holes dropped, length 4
JSON.stringify(a);          // '[1,2,3,null,null,6]'
[...a];                     // [1, 2, 3, undefined, undefined, 6]
a.includes(undefined);      // true  — includes does not skip holes
a.indexOf(undefined);       // -1    — indexOf does skip them

That last pair is the trap: the same array answers "is undefined in here?" two different ways depending on which method you reach for.

The default comparator

JavaScript
[10, 2, 1, 21].sort();                 // [1, 10, 2, 21]
[10, 2, 1, 21].sort((a, b) => a - b);  // [1, 2, 10, 21]

sort with no comparator converts both operands with ToString and compares UTF-16 code units, so "10" < "2". It has been stable since ES2019, which is exactly why the bug survives review: the order is deterministic and looks intentional until a two-digit value appears.

Failure modes

  • Sorting numbers without a comparator. Passes casual testing because the happy path hides it; the input distribution that would expose it is what a quick check leaves out.
  • delete arr[i] to remove an element. Leaves a hole, drops the array to holey, and length does not change.
  • new Array(n) then index assignment. map/forEach silently skip the holes, so a transform that "should" produce n results produces fewer.
  • a.length = n to trim. Silent, irreversible data loss: fine as a.length = 0 for reuse, dangerous as a partial trim.
  • JSON round-trip. Holes serialize to null, so a sparse array does not survive JSON.stringify/parse.

What to do

Build with push or Array.from, not index assignment past the end. Pass a comparator to every sort. Use at(-1) instead of length - 1. If you need a real element count on a possibly-sparse array, keep it yourself or use a Map: length will not give it to you.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How would you review a pull request whose risk is shallow copies, deep copies, and structuredClone?

Answer

The 90-second version

I review it as an aliasing review, not a style pass. Three passes:

  1. Grep the diff for the copy idioms ({...x}, Object.assign, JSON.parse(JSON.stringify(x)), structuredClone(x)) and for each hit ask one question: after this line, who owns the nested object? If the answer is "both the caller and the callee", that's the finding.
  2. Check whether the copy crosses a boundary the other side can mutate: a store, a cache, a worker postMessage, a request handler, a React state setter. A shared reference inside one function is a latent bug; a shared reference across a boundary is an incident.
  3. Ask for one test per copy site that mutates the copy and asserts the original is unchanged. If the author can't write it, the copy isn't understood.

What each idiom actually guarantees

IdiomDepthPreservesLoses / throws
{...x}, Object.assign1 levelown enumerable propsnested refs shared; prototype lost
JSON.parse(JSON.stringify(x))deepplain dataundefined/functions/symbols dropped, Date→string, Map/Set→{}, NaN/Infinity→null, throws on cycles and BigInt
structuredClone(x)deepcycles, Date, Map, Set, RegExp, typed arrays, ArrayBufferprototype lost (class instance → plain object); throws DataCloneError on functions and DOM nodes; symbol-keyed props dropped

Comments I actually leave

  • On a spread of a nested config: "{...config} shares config.retries. Line 40 mutates copy.retries.max, which writes through to the caller's object. Either clone retries too or document that the caller must not reuse it."
  • On a JSON round trip used to snapshot a request body: "This turns createdAt into a string and drops undefined fields. If anything downstream calls .getTime() it breaks. structuredClone keeps the Date."
  • On structuredClone of a class instance: "This returns a plain object. instanceof Order is false and the methods are gone. If you need the prototype, clone the fields into a new Order."

The test I ask for

JavaScript
const original = { items: [{ qty: 1 }], at: new Date(0) };
const copy = structuredClone(original);
copy.items[0].qty = 99;
copy.at.setFullYear(1999);
// assert original.items[0].qty === 1
// assert original.at.getFullYear() === 1970

For a shallow copy the same test fails on the first assertion: that's the point. For a JSON round trip, copy.at is a string and setFullYear throws, so the failure surfaces in the test rather than in production.

Failure modes and how they show up

  • Draft/derived state leak: a form draft spread from a saved record; editing the draft mutates the record, and the bug appears only when the user saves twice.
  • Cache poisoning: a cached object handed out by reference; one caller mutates it and every later reader sees the change. Detected by a test that reads the cache twice with a mutation in between.
  • Silent type change from JSON: dates become strings, Map becomes {}; detected by asserting instanceof on the copy, not just deep equality.

When not to demand a deep copy

structuredClone on a large graph is not free: it walks and allocates the whole structure, so on a hot path it can dominate the profile. If the data is genuinely immutable, Object.freeze in dev plus a shared reference is cheaper and correct. The review question is not "is this deep enough" but "who is allowed to mutate this after the copy", and if the answer is nobody, the copy may be unnecessary.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you brief product on why iteration protocols delays a ship date?

Answer

Product doesn't need the iteration protocol. They need the decision, the date, and the cost of each option. The 90-second version: "We found a bug in the ingestion path on Tuesday. It's silent data corruption, not a crash, so we can't ship it behind a flag. Fix plus regression coverage is 2.5 days, staging verification is 1 day, half a day of buffer: that moves the date from the 14th to the 18th. The alternative is shipping on the 14th with a workaround that's correct for today's payload shape but untested for nested items. I don't recommend it. I need a yes on the 18th by Thursday."

Then the skeleton, because product will ask these in roughly this order:

Product's questionWhat you say
What happened?One sentence, no mechanism: "A refactor changed how we walk the API response and it drops records."
How bad?Blast radius: which customers, which payloads, silent or loud.
What does it cost?Days, and what else slips with them.
What are my options?Two, maximum, with a recommendation attached to each.
What do you need from me?A specific decision and a deadline for it.

Keep the mechanism for the follow-up, because "why does that take 2.5 days?" is the question that decides whether they trust the estimate. The cause:

JavaScript
const res = JSON.parse('{"items":{"a":1,"b":2}}');
for (const item of res.items) {}   // TypeError: res.items is not iterable

res.items is a plain object. for...of looks for Symbol.iterator on it, finds none, and throws. The previous code path used a generator that yielded entries lazily; the refactor replaced it with a direct loop over the object, which never worked: it just wasn't exercised, because the test fixture had an array where production sends an object. The fix is one line:

JavaScript
for (const [id, item] of Object.entries(res.items)) {}

Trace it: Object.entries returns [["a",1],["b",2]]; each pair destructures into id and item; two iterations, no throw. That's the whole fix. The 2.5 days is the regression test that would have caught it, a fixture with an object-shaped items, plus auditing the four other call sites that share the helper.

The trade-offs, and the criteria that decide them:

  • Ship on time with the workaround. Acceptable only if the failure is loud (a throw you'd see in the first minute) and the workaround is provably equivalent for every payload shape you can enumerate. Here it isn't: the bug is silent, so a wrong record looks exactly like a right one.
  • Delay. Costs four days of schedule, buys a test that pins the contract. Choose it when the failure is silent, or when the payload shape is controlled by the customer rather than by you.
  • The deciding question is never "how long is the fix." It's "if this is wrong in production, how do we find out?" If the answer is "a customer tells us," you delay.

Failure modes of the briefing itself: leading with the mechanism (product stops listening at Symbol.iterator), burying the new date in paragraph three, presenting a single option so it reads as a notification rather than a decision, and leaving without an explicit ask. You detect all four the same way: ask product to repeat the date and the decision back to you before you leave the room. If they can't, the briefing failed, not the estimate.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the smallest experiment that would change your mind about the event loop and the microtask queue?

Answer

The model under test: one task runs to completion, then the microtask queue drains to empty, including microtasks enqueued by microtasks, before the next task starts.

The experiment. One file, four lines of output, no framework:

JavaScript
setTimeout(() => console.log("task"), 0);
Promise.resolve().then(() => {
  console.log("m1");
  Promise.resolve().then(() => console.log("m2"));
});
console.log("sync");

Prediction if the model holds: sync, m1, m2, task.

Trace it the way the engine runs it. The script body is the first task: sync prints, the stack empties, and the microtask checkpoint runs. m1 prints and enqueues m2; the queue is not empty, so m2 prints inside the same checkpoint. Only then does the timer task run.

Falsifier: sync, m1, task, m2. That would mean the queue drains one level per turn, and every ordering argument built on "microtasks finish first" needs rewriting. One observation, one revision: that is the whole experiment.

Second experiment, for the task boundary. The model also claims a timer callback is a task, not a microtask, and that setTimeout(fn, 0) is not 0 ms:

JavaScript
let n = 0, t0;
function tick() {
  if (n === 5) t0 = performance.now();
  if (n === 6) console.log(performance.now() - t0);
  if (++n < 8) setTimeout(tick, 0);
}
setTimeout(tick, 0);

Expect roughly 4 ms between the sixth and seventh callbacks in a browser: the HTML spec clamps a timer to 4 ms once its nesting level exceeds 5, and the seventh callback was scheduled at nesting level 6. Node has no such clamp and floors the delay at 1 ms. If you measure ~0.1 ms, the clamp is not firing and "0 means 0" is wrong.

Where the experiment lies. A then callback and an await continuation land in the same queue, so swapping one for the other changes nothing: that is not a falsifier. Console grouping and breakpoints change what you see, not the order. And the two snippets behave differently in Node, where timers run in a dedicated phase rather than between rendering opportunities.

What it does not settle. Whether microtasks run between two listeners on the same event. They do: the checkpoint runs after each callback once the stack empties. Test it with two click listeners, the first queueing a microtask and the second logging: the microtask prints between them. Cost is also outside this experiment. For that, the Long Tasks API reports any task over 50 ms, which is the number to watch when a handler you called fast freezes the UI.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does promises and error propagation interact with rollback, and where do people ignore that?

Answer

Core. A rejection is a control-flow signal; rollback is a side effect you have to trigger. Promises propagate the first and do nothing about the second. await inside try is what gives you a lexical place to run the compensating action with the right handle in scope, but the rejection arrives after the write has already committed, so the rollback is always a compensating action, never a prevention.

Mechanism. A promise settles once. .then, .catch, .finally each return a new promise, so a rejection travels down the chain until a handler consumes it. A handler that returns a value resolves the next promise; one that throws rejects it. If no handler consumes it before the microtask queue drains, Node's default (--unhandled-rejections=throw since Node 15) terminates the process with a non-zero exit. That default is itself a rollback of last resort: killing the process closes the connection and the database aborts the open transaction. It does nothing for work already committed in another service.

The interaction, in code.

JavaScript
async function transfer(db, from, to, amount) {
  const tx = await db.begin();                 // BEGIN
  try {
    await tx.query("UPDATE acct SET bal = bal - $1 WHERE id = $2", [amount, from]);
    await tx.query("UPDATE acct SET bal = bal + $1 WHERE id = $2", [amount, to]);
    await tx.commit();
  } catch (e) {
    await tx.rollback();                       // ROLLBACK, awaited
    throw e;                                   // re-reject to the caller
  }
}

Trace: the second UPDATE rejects (say a CHECK constraint). Control jumps to catch, await tx.rollback() sends ROLLBACK and the first UPDATE is undone, then throw e rejects the promise transfer returned, so the caller's await transfer(...) sees the error. Drop the await on rollback() and the function rejects before ROLLBACK is sent; the pool can hand that connection to another request with the transaction still open: visible as idle in transaction rows in pg_stat_activity.

Where people ignore it.

  • try { failing(); } catch {} without await catches nothing. The function returns before the rejection happens; the error surfaces as an unhandled rejection and no rollback runs.
  • Promise.all([chargeCard(), reserveStock()]) rejects on the first failure, but the other promise keeps running and can commit. Your catch rolls back the database; the stock reservation in another service is untouched. Promise.allSettled is what lets you compensate everything.
  • .finally is not a rollback hook. It runs on both paths, receives no rejection, and a throw inside it replaces the original error, losing the cause.
  • Fire-and-forget doThing().catch(log) returns 200 to the client before the compensation runs.

Trade-offs. Single-datastore transaction rollback is atomic, server-side and cheap, but holds locks for the transaction's duration and covers one resource only. Cross-service compensation is eventually consistent, needs idempotency keys and a durable log, and cannot undo an email already sent. Promise.all is fastest but leaves orphans; sequential await makes rollback ordering trivial but serialises latency. The deciding question: does every side effect live in one transactional resource? If yes, await the rollback. If any effect is non-transactional, you need compensation, not rollback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites await, sequential or concurrent but cannot apply it?

Answer

I'd stop asking them to define things and hand them a snippet with a number attached.

The question: "This handler fetches 20 items from a downstream service. Each call takes about 100 ms. It currently takes about 2 s. Make it fast. Then tell me the conditions under which your change is wrong."

JavaScript
async function load(ids) {
  const out = [];
  for (const id of ids) out.push(await fetchOne(id));
  return out;
}

What I listen for, in order:

  1. Do they ask whether the calls are independent before touching the code? If fetchOne(id) for id 5 needs the result of id 4, Promise.all is a correctness bug, not an optimization. A reciter reaches for Promise.all on reflex; an applier asks first.
  2. Do they name the mechanism rather than the slogan? ids.map((id) => fetchOne(id)) starts all 20 promises synchronously; Promise.all then waits for the last to settle. About 100 ms, not 2 s. The loop version starts call n+1 only after call n settles, so the latencies add.
  3. Do they know what Promise.all does on failure? It rejects on the first rejection, but the other 19 requests are already in flight and keep running. There is no cancellation. If the caller retries the whole batch, you have doubled the load on a service that just failed.

Then the second half, which is where the reciter falls over: "when is your change wrong?"

Strong answers: when the downstream has a connection pool or a rate limit. 20 concurrent calls is fine; 5,000 is not. Unbounded Promise.all over a large collection exhausts the pool and p99 climbs: the fix that made 20 items fast makes 5,000 items slower and flakier. The bounded version:

JavaScript
async function mapLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;
  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
    while (next < items.length) {
      const i = next++;
      results[i] = await fn(items[i]);
    }
  });
  await Promise.all(workers);
  return results;
}

next++ runs synchronously before the await, so no two workers claim the same index; with limit = 3 and 10 items, at most 3 calls are in flight at any moment.

Also strong: partial failure. If 3 of 20 failing should still return the other 17, Promise.all is the wrong tool: allSettled keeps the rejections, and the candidate should say which behaviour the product wants.

Weak answers: "await is blocking" (it isn't. The thread runs other work; the cost is added latency inside this function), or "just use Promise.all" with no mention of independence, failure semantics, or bounds.

Follow-up I'd use to separate the two: "the service now returns 429s under load. What changes?" A reciter has nothing; an applier reaches for a concurrency cap and a retry with backoff, and knows the retry has to respect the same cap.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document modules, live bindings, and cycles so the next owner can operate it?

Answer

I keep one page per package in the repo (docs/modules.md, reviewed in the same PR as the code) with three fixed sections, and CI checks that fail when the page and the code disagree. In the first minute the next owner needs three answers: who may import whom, which exports are reassignable, and which cycles are deliberate and in what order they evaluate.

1. Module map. A table, not a paragraph. Four columns:

ModuleOwnsPublic exports (kind)May import
src/registry.mjsthe one shared cachecache (const), get(k) (function)nothing
src/config.mjsenv parsingconfig (const), reload() (function)registry
src/counter.mjscounter statecount (let), bump() (function)config

The kind column is the load-bearing part. let beside count says every importer holds a live binding whose value changes under it after import: a debugging fact you cannot recover quickly from a 40-module graph. The last column makes direction explicit; registry importing config would show up as a diff against the table.

2. Live bindings, in four lines and a snippet.

ESMCommonJS
Import of a later-reassigned bindinglive binding, reads the new valuecopy taken at require time, stays at the old value
Reading a const export mid-cycleReferenceError: Cannot access 'x' before initializationpartial module.exports, often {}
JavaScript
// counter.mjs
export let count = 0;
export const bump = () => { count += 1; };

// main.mjs
import { count, bump } from "./counter.mjs";
bump();
console.log(count);   // 1 — live binding
// const { count } = require("./counter.cjs") after the same bump still reads 0

If the package is ever consumed both ways, one line names the dual-package hazard: require and import can load separate module instances with separate caches, so "shared state" is only shared per graph.

3. Cycle register. Each cycle gets an entry containing the exact evaluation order it produces, because "cycles are fine if you are careful" is not operable.

JavaScript
// a.mjs
import { bValue } from "./b.mjs";
export function aFn() { return "aFn"; }
export const aValue = "A";
console.log("a body:", bValue);

// b.mjs
import { aFn } from "./a.mjs";
export const bValue = "B";
console.log("b body:", aFn());

node a.mjs prints, in order:

b body: aFn
a body: B

b's body runs first, because the entry module pulls its dependency in before its own body executes. aFn is readable because function declarations are initialized during instantiation. Swap it for aValue and the run produces no output at all and exits 1 with ReferenceError: Cannot access 'aValue' before initialization thrown from b.mjs. The register states that rule once: inside a cycle you may read a function declaration or a var from a module whose body has not run; let, const and class throw. That sentence is what stops the next owner from "fixing" ordering with a setTimeout.

When a cycle exists only to share one instance, the entry names the sentinel instead: registry.mjs imports nothing, so both modules should import the registry and the cycle entry can be deleted.

4. Interop line and guards. State the runtime the service is pinned to; require(esm) is enabled by default from Node 22.12.0, backported to 20.19.0, and requiring a module with top-level await throws ERR_REQUIRE_ASYNC_MODULE rather than waiting. CI runs npx madge --circular --extensions js,mjs,ts src, which exits non-zero on a new cycle, plus eslint-plugin-import's import/no-cycle with maxDepth bounded to the depth you accept; the madge output is pasted into the register rather than hand-maintained.

The one process rule: the PR template asks whether the change adds an import that points against the table or introduces a cycle. Unchecked, it gets an entry. That is the whole maintenance story: the page describes intent, the linters catch drift.

Curated: · Written: · Reviewed:

Difficulty: Hard