+ 4

Need help with javascript code snippet

for (var a = 1; a < 5; a++) { setTimeout(function(){ console.log(a)},1000); } why is the output of above code snippet is 5 5 5 5 and not 1 2 3 4? Can anyone please explain it.. if i use "let" keyword then it returns 1 2 3 4 for (let a = 1; a < 5; a++) { setTimeout(function(){ console.log(a)},1000); }

12th May 2022, 7:36 AM
Edwin
Edwin - avatar
2 Antworten
+ 7
Because var is a global scope variable so after becoming a = 5, on every second 5 will be print And let is a blocked scope variable so after becoming a = 5, it will be start again with 1 so 2nd one is printing 1, 2, 3, 4
12th May 2022, 8:27 AM
A͢J
A͢J - avatar
+ 3
Because of the event queue in JavaScript, the setTimeout callback function is called after the loop has been executed. Since the variable i in the first loop was declared using the var keyword, this value was global. During the loop, we incremented the value of i by 1 each time, using the unary operator ++. By the time the setTimeout callback function was invoked, i was equal to 5 in the first example. In the second loop, the variable i was declared using the let keyword: variables declared with the let (and const) keyword are block-scoped (a block is anything between { }). During each iteration, i will have a new value, and each value is scoped inside the loop.
12th May 2022, 10:19 AM
Lambda
Lambda - avatar