DEV Community

Djilou
Djilou

Posted on

Some deep diving in JS concepts

There is no need to tell you that JavaScript has some unexpected behaviors sometimes and it's so frustrating when we don't understand them and get what's going.In this post we will explore one of them and hopefully fully understand it !

for (var val = 0; val < 10; val++) {
console.log(val);
setTimeout(function() {
console.log(
The number is ${val});
}, 1000);
}

this above for loop will print

0
1
2
3
4
5
6
7
8
9
"The number is 10"
"The number is 10"
"The number is 10"
"The number is 10"
"The number is 10"
"The number is 10"
"The number is 10"
"The number is 10"
"The number is 10"
"The number is 10"

and the same for loop but with let instead of var will print

0
1
2
3
4
5
6
7
8
9
"The number is 0"
"The number is 1"
"The number is 2"
"The number is 3"
"The number is 4"
"The number is 5"
"The number is 6"
"The number is 7"
"The number is 8"
"The number is 9"

The question is : why there are different behaviors ?

First thing to know :

important:The setTimeout API will only start executing the callback function once all the global synchronous code has executed,so setTimeout API will register the function as callback 10 times.

Second thing:
Declaring a variable with var (outside of a block) will define it in the global scope and declaring it with let will declare it into the local scope

You started to get it right ?(if you still didn't,don't worry i'll break it to you)

In the loop with var declaration,the callback function of setTimeout will have to wait for the global scope operations to finish (i value changing and the console.log(i)) before being able to execute.

And in the let declaration version , "i" variable is locally declared (local scope) so it's changes won't block the setTimeout callbacks execution.

That's it hope you enjoyed reading this post,Happy coding.

SOURCE:https://discuss.codecademy.com/t/var-and-let-in-a-loop-working-differently/550468/8

Top comments (0)