code

JavaScript Variables. What to choose? Var, let or const? And why const?

JavaScript

Once there was no dispute over how to declare variables, there was the only var. However, since the coming of ES 6 things complicated, but why?

Var made problems from the start, most importantly because there was no differentiating between constant and variable and the biggest problem for programmers was the range of var variables.

JavaScript Variables

Var has a range of a whole function caused illegibility in code and a headache while considering where did this variable came from? Amongst other things, this is why we never use var!

So, what to choose? Let or const?

In the case of let and const range of variables is from bracket to bracket, which solves most problems, but to choose correctly you have to dig deep into the purpose of a declaration. Keyword let, allows us to create a variable in which we can change reference, unlike const. Const additionally forbids us from assigning variables again. What that entails is that whenever we want to declare a simple type (string, boolean, number, etc.), which we would want to change in the future, we should use let. When we would want to create a constant value, we use const.

What about reference type?

In those we always use const. The change of the value of a field in an object or the value of an array element will not change the reference. It is one of the most common mistakes made by starting programmers. When they make an array or an object, they declare using let, because they will want to change values inside. They couldn’t be more wrong. Keyword const, as mentioned before is used to assign reference, meaning to point to a specific “object” in memory. We cannot assign a new “object “to const but we may edit it (add/delete/edit elements of arrays and objects).

Why is it best to use only const?

The answer is simple, it is way easier to manipulate code. When we use a lot of variables declared using let, often we have to check step by step if something is not being overwritten somewhere. When we use const, every next attribution is considered an error by our beloved compiler and shown with a beautiful red caption.

Someone might ask, “Then how am I supposed to assign something to the const variable when I don’t yet know what is supposed to be there”.

avatar
Konrad Odo
14/10/2021
ebook