Why am I not achieving the sphere for this code and ending up getting 66666? Give the surface and deep reason why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why am I not achieving the sphere for this code and ending up getting 66666? Give the surface and deep reason why?

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

18th Jun 2019, 6:50 PM
Athman Hassan
Athman Hassan - avatar
2 Answers
+ 1
It's because you used the var keyword. It will just look at the variable i and say, "hm, it looks like 6 to me", and outputs 6. But if you use the let keyword, there won't be a variable i, so it just says what it was told to say Please use relevant tags xx byesies
18th Jun 2019, 7:12 PM
Airree
Airree - avatar
+ 1
this is javascript, not java. for() loop 5x initialise print i value with console.log(i) but each call of print function is executed after next i*1000 ms by setTimeout() . In first 1*1000 ms for() loop ends with value i=6. Then it first prints i and then repeatedly every i*1000ms. try this modification var a = 1; for (var i=1; i<=5; i++) { setTimeout (function(){ console.log ("a:" + a++); }, i*1000); console.log("i:" + i); } console.log("ends with i:" + i); i:1 i:2 i:3 i:4 i:5 ends with i:6 a:1 a:2 a:3 a:4 a:5
18th Jun 2019, 7:59 PM
zemiak