As an old teacher of mine would say:
Don’t confuse "archipelago of Fernando de Noronha" with "skinny marijuana smoker". They may sound alike, but they’re completely different.
He said that basically in the sense that not everything is what it seems.
The term const
in Javascript defines a reference constant to an object. That is, the reference cannot be overwritten. Once the reference points to an object, it cannot receive another object.
const number = 2;
number = 3;
Note that trying to overwrite the object in number
gives error. However, being constant is different from being immutable. An immovable object cannot mutate and, "if it suffers", defines another object. For example, if I have the integer, which is immutable, 1, and I increment it into a unit I move to object 2, which is independent of original 1. Therefore, even assuming it as constant, I cannot modify it:
const number = 1;
number++;
The same error will be presented, because the object will be constant and immutable, different from a array He’s a changeable guy. Even giving it a constant reference, the object remains mutable, allowing it to mutate without representing another object:
const arr = [];
arr.push(1);
console.log(arr);
To MDN documentation comments on:
The statement const
creates a read-only reference to a value. This does not mean that this value is immutable, only that the identifier of the constant variable cannot be changed. If the content of the identifier is an object, the parameters of that object may be changed, for example.
Other interesting readings:
If you prefer something more official:
If it is constant I say with the nerves. What would be the need to change a value that we will declare as
const
?– lazyFox
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.
– Maniero