Changing a const array

Hello there,

in the basic java script curriculum (step: Modify Array Data With Indexes) i have to change the first value of a array. the array is initially declared as a constant.

const myArray = [18, 64, 99];

// Only change code below this line
myArray[0] = 45;

my question: why can i change the value of a constant after initialization? Isn’t a constant supposed to be read only? Thanks in advance for your help!

Edit: in addition to snowmonkey: see const - JavaScript | MDN

The array structure itself is the const-ed bit. It looks odd, but the fact that myArray is a const means we can’t myArray=[45, 64, 99] - we can’t reassign the variable itself. The contents of the array are not fixed with the const statement though.

If we wanted to fix the contents of an array, remember that an array is a specialized type of object: Object.freeze() - JavaScript | MDN

3 Likes

Yeah the problem is the interaction of const and arrays.
I’d need to look up myself, how exactly it works.
The thing is, an “array” is an object, think like a jar in real life. And “const” means you cannot change the jar, but you can change what’s inside.
And “inside” the array are hidden lines of code, hundreds of them. All there to allow you transformations and other things to do with the array - and appearently people decided that const should not affect those. Which most likely is rooted in it’s use-cases. But again, I’d need to look up myself, what these use-cases are that lead to this decision. Either that or it’s just “programmically” impossible (or at least very complicated) to lock-down the entire content of the array based on how it’s structured within the memory.

2 Likes

An array is simply an object, like any other object. The only time it becomes a bit more complex to use Object.freeze() on an array? If it’s an array of objects. Freezing a top-level object does not freeze any of the nested objects within it. :wink:

2 Likes