+ 2
why its output is 10???
for(var i = 0;i < 10;i++) setTimeout(() => { console.log(i) }, i * 1000);
13 Respuestas
+ 4
Shushan , it's normal behavior if we consider the setTimeout method. There is call to a anonymous function inside the loop, which is executed after the delay i* 1000 ms =>i * 1s (on each step the timeout is updated with new value => 0s, 1s,..., 9s) . So the final value of i is 10=> which is printed on console in fact 10 times. You can find more info about this method here: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
+ 1
But if I wiIl write let instead of var it will work like I said from 0 to 9 ...
the problem here is var
+ 1
Shushan , let declares block scope variable, var function scope variable. You can find more info here: https://www.google.com.br/amp/s/www.geeksforgeeks.org/difference-between-var-and-let-in-javascript/amp/
+ 1
It will create error.
+ 1
just your output is 0_9. if you wanna print output 10 you should write 1<=10
0
Mirielle from 0 to 9
0
Mirielle , I think it is just a challenge question in JS. I met this question a few times.
0
Mirielle , yes I think the question is about maybe the strange output at first sight 😺
0
TheWh¡teCat thanx🙂
0
Shushan , you are welcome 😺