JavaScript Closure & Hoisting: Understanding Variable Scope

💡 JavaScript Interview Question: Closure & Hoisting Interviewers often ask this question to test understanding of closures and variable scope. for (var i = 0; i < 3; i++) {  setTimeout(() => {   console.log(i);  }, 0); } 👉 Output 3 3 3 Reason: `var` is **function-scoped**, so all callbacks share the same variable `i`. By the time `setTimeout` executes, the loop has already finished and `i` becomes `3`. --- ### Common Fix Most candidates change `var` to `let`: for (let i = 0; i < 3; i++) {  setTimeout(() => {   console.log(i);  }, 0); } 👉 Output 0 1 2 This works because `let` is **block-scoped**, creating a new `i` for each iteration. ### The Real Twist Sometimes the interviewer says: **“You cannot use `let`.”** In that case, we can create a new scope using a function. function logger(i) {  setTimeout(() => {   console.log(i);  }, 0); } for (var i = 0; i < 3; i++) {  logger(i); } 👉 Output 0 1 2 Each call to `logger(i)` creates a new scope and preserves the value of `i` using **closure**. If you got it, give a thumbs up! #javascript #frontend #elsecoder

Other ways - for (var i = 0; i < 3; i++) { let j= i; setTimeout(()=> console.log(j)); } // Output: 0, 1, 2 for (var i = 0; i < 3; i++) { setTimeout(console.log, 0, i); } // Output: 0, 1, 2 for (var i = 0; i < 3; i++) { setTimeout(console.log.bind(null, i), 0); } // Output: 0, 1, 2

To view or add a comment, sign in

Explore content categories