6 Advanced JavaScript Questions That Separate Seniors from Mid-Levels
1. Stale closure & primitive capture What is the output of the following code? function createIncrement () { let count = 0 ; const message = `Count is ${ count } ` ; function increment () { count ++ ; } function log () { console . log ( message ); } return { increment , log }; } const { increment , log } = createIncrement (); increment (); increment (); log (); Test your understanding of closures, lexical scope, and primitive value capture. ✅ Output Count is 0 🧠 Explanation This is a classic stale closure trap — but not in the way most developers expect. Step-by-step execution: createIncrement() is invoked → new lexical environment created: count = 0 (mutable binding) message = "Count is 0" (primitive string, interpolated immediately at assignment) Inner functions increment and log are defined. Both close over the same lexical environment. increment() is called twice: count mutates: 0 → 1 → 2 ✓ This works as expected. log() is called: It references the variable message message still holds the original string value "Count is 0" The template literal was evaluated once, at the moment of assignment — not re-evaluated when log() runs. 🔑 Core Concept > Closures capture variables , not expressions . > But if a variable holds a primitive value (string, number, boolean), that value is fixed at assignment time. message is not a live reference to count . It is a snapshot . 🛠 How to fix it (if dynamic output is desired) Re-evaluate the template literal inside log() : function log () { console . log ( `Count is ${ count } ` ); } 🎯 What this question tests Concept Why it matters Template literal evaluation timing They run at assignment, not at access Primitive vs reference types Primitives are copied by value; objects/arrays are referenced Closure capture semantics Closures close over bindings, but the value of a primitive is immutable once assigned Mental model of "live" variables Not all variables in a closure are "live views" — only the bindings themselves are 2. JavaScript co