Does JavaScript treat loops differently when you use let and differently when you use var? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Does JavaScript treat loops differently when you use let and differently when you use var?

I'm trying to understand why for(var x = 0; x<3; x++){ setTimeout(() => console.log(x), 2000) } Works differently than for(let x = 0; x<3; x++){ setTimeout(() => console.log(x), 2000) }

8th Dec 2020, 12:16 PM
Karak10
Karak10 - avatar
5 Answers
+ 2
Well, I have something in mind, not sure if it's the answer: in every loop scenario .. the function in the first argument of "setTimeout()" is thrown to the browser so it's done afrer the specefied time (2000 ms) however, both scenarios differ in the following: when function is excuted by the browser the "x" variable is looked at in the block level: knowing that "var" has no block level except functions .. its value is taken from the last update recorded for the global variable X which is after 2000ms (the loop will end way before this leaving x = 3, it just throws the function to the browser in the end) this.. when the function is executed after two seconds .. x value is 3 for every call. that's is not the case for "let".. because its scope is limited to the for loop block, thus .. its value must be thrown away alongside the function in every run (every function remembers its lexical environment) I know my answer is so complicated, but your question scratches the surface of many deep aspects of the language, as event loop, asynchronous and synchronous excution and variables scopes
8th Dec 2020, 2:14 PM
Ali Kh
Ali Kh - avatar
+ 3
Read Morpheus's explanation and David Carroll's shared articles. https://www.sololearn.com/post/91896/?ref=app https://www.sololearn.com/post/91113/?ref=app
8th Dec 2020, 5:10 PM
Gordon
Gordon - avatar
8th Dec 2020, 2:08 PM
Jayakrishna 🇮🇳
0
I'm not sure if I got it right or not, is this what happens behind the scenes? https://code.sololearn.com/WgwRxAY2IHNq/?ref=app
8th Dec 2020, 1:12 PM
Karak10
Karak10 - avatar
0
Ali Kh I'm not yet very sure but I think those three examples I made demonstrate what exactly happens: https://code.sololearn.com/WgwRxAY2IHNq/?ref=app
8th Dec 2020, 2:44 PM
Karak10
Karak10 - avatar