Why is it possible to change constant values in JavaScript arrays?

2

Having the following code:

const arr = [1,2,3];
console.log(arr);
arr.push(4);
console.log(arr);
arr.pop();
console.log(arr);

How much of% should not be constant? And why should not you accept the method arr and push() ? After all, if I include or exclude an element of this array I'm changing its value, so it is not constant. Or am I misunderstanding the concept of constant in JS?

    
asked by anonymous 24.01.2018 / 13:55

1 answer

1

You need to understand the difference between types by value and types by reference . In types by value the content is in the variable, in types by reference the content is in another location, and the variable has only one pointer to that location.

The const refers to this value of what would be a variable (in this case is a constant). Then the code can not change the pointer stored there, ie you can not take that identifier and point to an object other than the one initially pointed to.

The contents of array are not constant, meaning what you have in the storage location can be changed as much as you want.

Now, as far as I know, there is no way to make the elements of arrays constant (there are tricks to indirectly achieve similar semantics).

You can even declare a variable and point to the same object. And being a variable, it can point to another object at any time, releasing itself from this object that already has a constant reference.

Therefore constancy (immutability would be a more appropriate term, JS, like many languages, does not press for the most correct terminology) is external to the object. Some languages allow internal "constancy."

Do not confuse the value associated with the identifier to the identifier itself. The identifier exists in the code, it's a word. The value exists at runtime and is where the code determines as specified. The identifier can not even, after all it does not exist, or does not matter, during execution (in JavaScript this is not true for all identifiers, but only for cases where the identifier is in the background a value, and if they create they create huge complicators , in practice it should not be done).

    
24.01.2018 / 14:20