Advertisement
728x90
javascript
1for (var i = 0; i < 4; i++) {
2 // global scope
3 setTimeout(() => console.log(i));
4 }
5
6for (let i = 0; i < 4; i++) {
7 // block scope
8 setTimeout(() => console.log(i));
9}The output of the above for loops is 4 4 4 4 and 0 1 2 3
Explanation: Due to the event queue/loop of javascript, the setTimeout callback function is called after the loop has been executed. Since the variable i is declared with the var keyword it became a global variable and the value was equal to 4 using iteration when the time setTimeout function is invoked. Hence, the output of the second loop is 4 4 4 4.
Whereas in the second loop, the variable i is declared as the let keyword it becomes a block scoped variable and it holds a new value(0, 1 ,2 3) for each iteration. Hence, the output of the first loop is 0 1 2 3.
Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 48
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
304of476