But there is a real difference between the three of them, and knowing which one to choose for your variable declarations can improve your quality of life as a developer.
What does this mean? Let’s demonstrate with some examples:
Redeclaring variables simply means we write the var, let or const keyword a second time. This is only possible with var.
This behaviour has some interesting implications for nested scopes. We can reuse a variable name for all 3 variable types, but var will overwrite the previous value, while let and const will be treated as a separate value in each scope:
Reassigning a variable means that we give an existing variable a new value. Only var and let variables are mutable.
A notable quirk is that array or object variables that were declared with const are still immutable, but their members are not.
Reading variables from outside the scope
When we declare a var inside some block scope, we can still access its value from outside that scope:
This is not the case with let and const variables:
To be continued…
Knowing the properties and behaviour of these different variable declaration keywords, makes it a lot easier to make an appropriate choice for each use-case.
My personal approach is to use const as much as possible, because this is the most restrictive variable type. For variables that must be mutable, I use let. On the other hand, var is a thing of the past for me because it is too permissive and can easily cause bugs in my code.