Vitaly Obolensky Posted on May 30 6 Advanced JavaScript Questions That Separate Seniors from Mid-Levels # javascript # webdev # interview 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 (); Enter fullscreen mode Exit fullscreen mode Test your understanding of closures, lexical scope, and primitive value capture. ✅ Output Count is 0 Enter fullscreen mode Exit fullscreen mode 🧠 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 } ` ); } Enter fullscreen mode Exit fullscreen mode 🎯 What this question tests Concept Why it matters Template literal evaluation timing They run at assignment, not at access Primitive vs refere
Back to Home

6 Advanced JavaScript Questions That Separate Seniors from Mid-Levels
B
Blizine Admin
·2 min read·0 views
📰Dev.to — dev.to
B
Blizine Admin
View Profile Staff Writer