Why have almost all "var"s have been replaced with "let"s literally overnight?

Why have almost all "var"s have been replaced with "let"s literally overnight?
0.0 0

#1

Although I have looked up the difference between “let” and “var”, I am still curious as to why all "var"s have been changed to “let” s . Is there a reason this changed occurred seemingly overnight ? In the simplest terms possible, what is the difference between the two ? Or are they same thing practically ? Why are we using “let” now ?


#2

Took about 5 or 6 years,and officially in spec from ECMAScript 2015. It was supposed to be part of ECMAScript 4 (which never reached a point of release and was scrapped, went straight to ECMAScript 5), and work on that started about 1999.

var is broken in several ways, but it can’t be deprecated because most of the JS in existance depends on it. Once let was supported almost everywhere, which is now, makes sense for everyone to use it.

var is only scoped to the nearest function (for example, if you have a loop in a function like for (var i = 0; i < ..., i is accessible anywhere inside the function. This means values can leak very easily. let is scoped to the nearest block (it has a smaller scope), if you replaced var with let the variable would not be accessible outside the loop.

var can be redeclared within a scope: var foo = 1; var foo = 2; is valid. let will throw an error if you do that, which cuts down on bugs.

var is available in a scope before it has been declared in the code, let will throw an error if you try to do that.

There are a few other things as well. Basically, it cuts down the number of errors you can make. Note as well that ideally you normally want to use const for everything you possibly can, reserving let for times when you specifically want a variable you can reassign values to (eg in a for loop).


#3

Lesson: Explore the differences between var and let keywords


#4

Thanks, I did not notice this challenge before. It clears things up.