🚀 30 Days — 30 Coding Mistakes Beginners Make Day 1/30 Why does this code print 3 3 3 ? (using `var` inside a loop with setTimeout) Because `var` is function scoped. The loop finishes first. After 1 second, all callbacks run… and they all read the SAME final value. Fix 👇 Use `let`. `let` creates a new variable for every loop iteration, so each callback remembers its own value. One keyword changed. Completely different behavior. Follow the series — tomorrow we fix another beginner mistake 🙂 #30DaysOfCode #javascript #reactjs #frontend #webdevelopment #codeinuse
Thanks for this.
The example is kinda of incorrect, if the for loop was inside a function then the var i is in function scope, in the example it is just a for loop by itself so the var i is actually in global scope.