Javascript: the weird parts (chapter 1 – var, let & const)

As a JavaScript developer, I believe it is important to be aware of some the language’s quirks. This is a list of some of the things I have compiled that might not be obvious to new or more experienced developers.

Variable declarations

When I talk to JavaScript developers who are not too familiar with ES6, this one comes up a lot. They get confused about whether to use var, let, or const, and so they resort to using var for everything.

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

Redeclaring variables simply means we write the var, let or const keyword a second time. This is only possible with var.

redeclaring a var works just fine
redeclaring let or const is not possible

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:

Reusing let or const variables in nested scopes will create separate entities for each variable.
Reusing var variables in a nested scope will overwrite the previous value.

Reassigning variables

Reassigning a variable means that we give an existing variable a new value. Only var and let variables are mutable.

var and let are mutable
const is immutable

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.

In the next chapter of JavaScript weirdness, I will try to clear up some of the confusion surrounding the this keyword.