DEV Community

Djilou
Djilou

Posted on

4 1

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay