Why for loop with setTimeout in JavaScript does not work the way we think Look at the simple code below: for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } We can assume here that the output will be: 0, 1, 2 But the actual output is: 3, 3, 3 If the code is without setTimeout: for (var i = 0; i < 3; i++) { console.log(i); } The result is clear: 0, 1, 2 And the same result for the below as well: for (let i = 0; i < 3; i++) { console.log(i); } Output: 0, 1, 2 Confused!! Earlier, I bypassed the concept and simply used let instead of var whenever I used any asynchronous callback inside a for loop, so the code worked fine. But at the same time, I wanted the reason for the different behavior. Let me share what I explored after a long time going deeper into JavaScript and how it plays with variable types - var and let where loop is concerned. In case of let, JavaScript creates a variable instance in memory for each loop iteration. Each setTimeout looks for its corresponding instance: Iteration 0 → i0 (instance) → value: 0 → captured by setTimeout 1 Iteration 1 → i1 (instance) → value: 1 → captured by setTimeout 2 Iteration 2 → i2 (instance) → value: 2 → captured by setTimeout 3 But in case of var, there will be only a single instance, which is updated on each iteration. Since setTimeout takes 100 ms to execute, by that time the loop is finished, so the setTimeout always sees the final result. #javascript #webdevelopment #frontend #reactjs #nextjs #axios #fetchapi #JavaScriptTraps #FrontendDevelopment #AsyncJavaScript #Closures #JavaScriptTips #JavaScriptGotchas #CodingConcepts #programmingtips #developercommunity #codinglife #softwareengineering #webdev #learnjavascript #techcontent #100daysofcode
333
var has a function scope, so it will set single variable where all iteration will be sharing it, so each iteration will find 3 is assigned to var i; So the answer after 100ms will be (3 3 3)
var is function-scoped no block scoped variable , so all callbacks share the same i. After the loop ends, i = 3, isliye output is 3 3 3
4 4 4 4 4
1-2
Pabitra Barua Why such kind of no brainer question still exists and why asking here? I know StackOverflow is dead but don’t you have charGPT to ask this question, if you are looking to learn? Humans are no longer needed for coding they are made to solve real problems
Let can solve it because it is new for every scope and we can also run immediately invoke function and pass a variable so the variable should be private to the function in iteration, just like a closure
Output: 3,3,3 Reson: var is function scope. It will update same variable during iteration and also setTimeout method will execute after delay and that time variable "I" become 3.
333