JavaScript Loop Bug: Understanding Scope and the Event Loop

What does this print? (Hint: Most developers get it wrong.) I thought I UNDERSTOOD JAVASCRIPT loops... until I saw this bug. 😅 Quick quiz: What does this code print? for (var i = 0; i < 3; i++) { setTimeout(() =>console.log(i), 1000); } If you said 0, 1, 2, you’re falling into the same trap I did early. THE ACTUAL OUTPUT IS 3, 3, 3. Why? It comes down to Scope and the Event Loop: var is function-scoped (not block-scoped). The setTimeout callback doesn't run until the loop has already finished. By the time the console logs, i has already been incremented to 3. The Fix? Simply switching to let (block-scoping) or using a closure. It’s a classic example of why understanding the engine under the hood is more important than just knowing the syntax. Have you ever been burned by var in a modern codebase? #JavaScript #WebDev #CodingTips #SoftwareEngineering

  • No alternative text description for this image

I don't think you understand JavaScript. It should give you syntax error. (this is for image code) Explanation is correct for correct syntax but syntax are incorrect.

Isn’t this just lambda capturing? Make a new var inside the loop and assign it to the i, then you can do whatever lambda function you want without issues (using that variable, not the i)

See more comments

To view or add a comment, sign in

Explore content categories