why its output is 10??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

why its output is 10???

for(var i = 0;i < 10;i++) setTimeout(() => { console.log(i) }, i * 1000);

3rd Oct 2019, 7:37 PM
Shushan
Shushan - avatar
10 Answers
+ 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
3rd Oct 2019, 7:50 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 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
3rd Oct 2019, 8:11 PM
Shushan
Shushan - avatar
+ 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/
3rd Oct 2019, 8:18 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 1
It will create error.
5th Oct 2019, 3:29 PM
Pushpendra Singh
Pushpendra Singh - avatar
+ 1
just your output is 0_9. if you wanna print output 10 you should write 1<=10
5th Oct 2019, 5:39 PM
Mostafa
Mostafa - avatar
0
Mirielle from 0 to 9
3rd Oct 2019, 8:02 PM
Shushan
Shushan - avatar
0
Mirielle , I think it is just a challenge question in JS. I met this question a few times.
3rd Oct 2019, 8:07 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
0
Mirielle , yes I think the question is about maybe the strange output at first sight 😺
3rd Oct 2019, 8:13 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
0
TheWh¡teCat thanx🙂
3rd Oct 2019, 8:28 PM
Shushan
Shushan - avatar
0
Shushan , you are welcome 😺
3rd Oct 2019, 8:30 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar