A question for my elders in JavaScript: putting aside the fact that let
has a different variable scope than var
does, it seems to me that in the vast majority of cases, there is no reason to use var
over let
. Of course, if you define a variable inside of an if
statement, it's not the same thing, but is there another reason besides scope to use one over the other?
Edit: To be clear, this question is about a best practice (i.e. pros and cons) in JavaScript, not about the nature of the differences between var
and let
.
Thanks!
No, I think there are no reasons. From what I've read, the var
is left in ES6 for backwards compatibility. Most of the articles I've read advise to gradually replace all var
occurrences with let
. Of course, this should be done accounting for differences such as the one you mentioned with if
block. I use only let
in my ES6 code now. Eric Elliott doesn't use var either. There’s nothing using var
that let
can’t do better. If you need entire function scoping, create the let
at the top of the function.
There is one difference that I've noticed. It is that when defining variables in the global scope, variables defined as var
are accessible with window.variable
, while variables with let
are not accessible using window
object. But with the properly written modular code, no var
statement should be allowed to leak to window
and so this has no importance.
I would also advise to use const
instead of let
for the cases when a variable reference (as opposed to a primitive variable's value) will not be mutated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With