DEV Community

Discussion on: Is`let` the new `var` in Javascript?

Collapse
 
mellen profile image
Matt Ellen • Edited

I think var should be used sparingly. Because of hoisting, you can be left in a state where you've accidentally put a value into a variable before you initialise it. Also var allows you to declare your variable multiple times, so perhaps, if you're forgetful like me, you'll accidentally use the same variable name for different things and end up confused as to why the variable has the wrong value.

Using let prevents all that.

I'm a firm believer in the practice of declaring variables as close as possible to where you will start using them. let allows that, var secretly prevents it.

Collapse
 
amitkhonde profile image
Amit Khonde

I also like to define the variables close to where they are being used. But I believe that if we declare the variables using var, we communicate that this variable is being used in the whole function body. I think it might be helpful to the code reader.

Collapse
 
mellen profile image
Matt Ellen • Edited

I can see how it could be useful to declare a var within an if, for example, if that's the first place it is used, as you can in python, but I think using var inside for, for example, opens you up to weird bugs.

I agree that in principle it is possible to use var responsibly. I still prefer let, as I know it'll be gone when my scope changes, so I don't have to think about it any more.