kooskoos
kooskoos

Reputation: 4879

Manipulating a const array

Why JS allows mutating const arrays?

e.g.

const a = 5
a = 6 //throws error

const arr = [1,2,3]
arr[2] = 4 // no error

Why is it allowed to mutate a const array when it should throw an error as in the first case?

Also how do I ensure that my array remains completely immutable?

Upvotes: 0

Views: 1779

Answers (2)

kooskoos
kooskoos

Reputation: 4879

It is allowed to add, delete or mutate const array in JS because arr variable stores the memory reference and not the values.

So even if you manipulate the values at that memory location you are not really changing the reference to the memory and hence the variable remains const.

The only thing that is not allowed is re-assigning the array arr = [] which essentially means changing the memory reference the arr variable stores.

As @Nina stated any kind of assignment to const variables is not allowed.

const arr = [1, 2, 3]

arr[2] = 4 //this is fine as memory reference is still the same
arr[3] = 3

console.log(arr)
arr = [] //throws error
console.log(arr)

Upvotes: 3

symlink
symlink

Reputation: 12218

A scalar value in Javascript is stored by value. For example:

let a = "foo" <--- a is linked to the value "foo"
let b = "foo" <--- b is also linked to the value "foo"

Objects and arrays are stored by reference. For example:

const arr = [1,2,3] <--- arr is linked to a unique address in memory that references 1, 2, and 3

When an array or object is mutated, the address in memory doesn't need to change:

arr.push(4) <-- arr is now [1,2,3,4], but its address in memory doesn't need to change, it's still just an array that references 1, 2, 3, and now 4

Upvotes: 0

Related Questions