Why var vs let matters in JavaScript loops and setTimeout

🚀 JavaScript Gotchas: var vs let in Loops & setTimeout Same code, different output 👇 Ever wondered why this code prints 5 5 5 5 5 instead of 0 1 2 3 4? for (var i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } 💡 Reason: var is function-scoped — only one i exists for the entire loop. setTimeout callbacks run after the loop finishes, so each callback sees the final value of i → 5. ✅ Fix it with let: for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } let is block-scoped — each iteration gets a new copy of i. Now, callbacks “remember” the correct value of i. ✅ Output: 0 1 2 3 4 💡 Key takeaway: var → shared variable in loop → tricky in async callbacks let → separate variable per iteration → safer & predictable ✨ Tip: Even setTimeout(..., 0) behaves the same! The event loop always runs callbacks after the current synchronous code. #JavaScript #CodingTips #FrontendDevelopment #WebDevelopment #Programming #LearnJS #DeveloperTips #AsyncJavaScript #Closures

  • No alternative text description for this image

Nice breakdown! let or const should be prefered in modern JS to get rid of such scoping issues.

See more comments

To view or add a comment, sign in

Explore content categories