Vineet Prajapati’s Post

🚀 My “Aha!” JavaScript Moment: Why does var print 3 three times? A few days ago, I was revisiting some JavaScript fundamentals… and I came across this classic piece of code 👇 for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } I expected: 0 1 2 But guess what I got? 3 3 3 😅 I paused for a second and thought — “Wait… what just happened?” 🧠 The Moment of Clarity Here’s what’s really going on: var in JavaScript is function-scoped, not block-scoped. So inside that for loop, all iterations share one single i variable. By the time the setTimeout callbacks actually run (after 1 second), the loop has already finished — and i has become 3. So all three callbacks look at the same i, and print 3. Boom 💥 — mystery solved. ✅ The Fix? Use let When we switch to let, something magical happens: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } Now, let is block-scoped, meaning each iteration gets its own copy of i. Each callback “remembers” the value from that iteration. Result: 0 1 2 💡 My Mental Model I now think of it like this: Using var: one whiteboard where you keep erasing and writing new numbers. Everyone who looks later sees the same final number. Using let: each student gets their own notepad — they all remember their own number. 🧩 Key Takeaway Keyword Scope Loop Behavior Output var Function-scoped Shared variable 3, 3, 3 let Block-scoped New variable each iteration 0, 1, 2 We often jump into frameworks, async/await, and APIs… but sometimes it’s these small, fundamental details that sharpen our understanding the most. 🔍 Have you ever had an “aha!” moment like this in JavaScript (or another language)? Share it below — I’d love to hear your story 👇 #JavaScript #WebDevelopment #AsyncJS #Frontend #FullStackDeveloper #LearningToCode #CodingJourney #Developers #CareerGrowth

To view or add a comment, sign in

Explore content categories