Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with for loop output in javascript [duplicate]

I'm reading You Don't Know JS book series.

In Ch.5 of Scope & Closure title of this book, there's this for loop i'm unable to understand

for (var i=1; i<=5; i++) {
setTimeout( function timer(){
    console.log( i );
}, i*1000 );}

It prints 6 in console 5 time after 1s interval. Even author is trying to explain why it's happening but i'm unable to get what he's trying to say.

You can find this code with explanation here: https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md

Head to 'Loop + Closure' section on the page you'll find this code.

Can anyone please explain me this in simple language?? Why it print 6 in console for 5 time instead of 1, 2,..., 5 after 1sec interval.

Thanks in Advance for your time & effort.

like image 567
Kishan Patel Avatar asked Dec 19 '25 06:12

Kishan Patel


2 Answers

Yeah because the loop runs through within the second and at that time the value of i is 6(with the last i++ which doesn't enter in the loop). hence it uses that value to render 5 times.

you can use following to print 1,2,3,4,5

for (let  i=1; i<=5; i++) {
setTimeout( function timer(){
    console.log( i );
}, i*1000 );}

with let you define scope of the i which is part of ES6

like image 171
K D Avatar answered Dec 21 '25 20:12

K D


This situation takes place because there is another scope in SetTimeoutFunction.

You can see your 1 2 3 4 5 if you use ES6 let.

for (let i=1; i<=5; i++) {
  setTimeout( function timer(){
    console.log( i );
  }, i*1000 );
}

Here you create special variable with let, which can be used inside SetTimeout scope.

like image 25
Grynets Avatar answered Dec 21 '25 19:12

Grynets



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!