JavaScript var vs let Execution Context

🎯 A JavaScript Interview Question About var vs let (Execution Context Perspective) In an interview, I was asked to explain the output of this code: for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } Output: 3 3 3 But when var is replaced with let: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } Output: 0 1 2 At first it looks like a setTimeout trick, but the real concept is about Execution Context and Scope. ⚙ Case 1 — Using var var is function-scoped, so the loop runs inside one execution context with one shared variable i. Visualizing it: Execution Context ----------------- i = 0 → timer scheduled i = 1 → timer scheduled i = 2 → timer scheduled i = 3 → loop finished All setTimeout callbacks reference the same variable i. When the timers finally execute after 1 second: console.log(i) console.log(i) console.log(i) The value of i is already 3. So the output becomes: 3 3 3 ⚙ Case 2 — Using let let is block-scoped. For every loop iteration, JavaScript creates a new lexical environment (new execution context for that variable). Visualizing it: Iteration 1 → i = 0 (separate context) Iteration 2 → i = 1 (separate context) Iteration 3 → i = 2 (separate context) Each setTimeout callback captures its own i value. When timers run: console.log(0) console.log(1) console.log(2) Output: 0 1 2 💡 Simple way to remember this var → one execution context → shared variable let → new lexical context per iteration → separate variable This question is often used in interviews to test understanding of: • Execution Context • Closures • Block Scope in JavaScript Small detail… but a powerful concept. #JavaScript #NodeJS #ExecutionContext #Closures #CodingInterview

  • No alternative text description for this image
See more comments

To view or add a comment, sign in

Explore content categories