Var and let difference

Var and let difference
0

#1

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


#2

#3

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.


#4

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


#5

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.


#6

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.


#7

You should read https://mathiasbynens.be/notes/es6-const if you get a chance. It’s not only about immutability.