Var and let difference

By using “let” I can print all the numbers in setTimeout but when I tried the same thing with “var” it printed “10” ten times
can anyone help ?

Output highlighted in yellow color in Picture

3 Likes

This involves the issue of scope. Var and let have different scoping. Var is scoped to the entire function block and let is only scope to the for loop.

2 Likes

I’m not sure how controversial this opinion is, but personally I consider var deprecated now and prefer to always use let.

3 Likes

I try to use const unless I know the variable will need to change in the future for example a for loop counter would use let.

1 Like

Marked as controversial by Isaac Abrahamson and 3 others. This opinion has been stated before three years ago and personally bothers my developer ego. If that barely related answer doesn’t satisfy your opinion, state it again and we will close it anyway.

Just kidding, I fully agree. I cringe every time I see var in my old code.

That’s a good approach. I personally just use let for everything and const explicitly when I want too. I feel that if I use const all the time it loses some value. When I declare a value as a constant, I want to know that I have a specific reason for doing so just by looking at it, and know that I will never, NEVER change that variable. If I just declare everything as const and then change to let, I can’t be 100% sure which variables are “special”. This probably makes no sense, but seems to work for me.

1 Like

You should read ES2015 const is not about immutability · Mathias Bynens if you get a chance. It’s not only about immutability.

1 Like