Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Since const is not usefull to create an immutable array in JavaScript (I don't know exactly why), what is the best way to create an Immutable array? [duplicate]

Tags:

javascript

This question has nothing to do with This question in my opinion, I'm trying to understand some behavior about the javascript core, I don't want a library or something.

I'm trying to understand why this code actually modify const originalArray

const originalArray = [0, 2, 1, 1, 1];

var newArray = originalArray;

var removed = newArray.splice(0,3);

console.log(originalArray);//return [ 1, 1 ]

But at the same time this is not possible:

const originalArray = [];
originalArray = [1];  

So, how can I create a truly immutable Array without a library?

like image 343
Emeeus Avatar asked Oct 17 '25 04:10

Emeeus


2 Answers

The reason modifying newArray also modifies originalArray is because variables in JavaScript are just references to objects. When you say newArray = originalArray, you're not copying the array, you're copying the reference. So when you say newArray.splice(0, 3), you're modifying the array referenced by newArray, which originalArray also references.

Similarly, in JavaScript, the word const refers to the reference being constant, not the underlying object. That is to say, you can call mutating methods like .splice on a const variable with no issues. It's when you try to reassign the variable using = or similar that you run into errors.

As others have noted, Object.freeze(_) will make it so you cannot modify the inner object, achieving "immutability" in that you will not be able to modify the underlying object.

For example, if you do the following:

const originalArray = Object.freeze([1, 2, 3]);
let newArray = originalArray; // you can easily use `const` here, but I don't want to confuse the two concepts
newArray.splice(0, 3); // TypeError: Cannot add/remove sealed array elements

If you want a copy of the array that you can modify without modifying the original array, Object.freeze alone will not help you. You will want to "deep copy" the array, which can be done through various methods (easily Google-able, so I will redact them as this answer is getting longer than hoped).

like image 166
River Tam Avatar answered Oct 19 '25 19:10

River Tam


You could use Object.freeze for that.

const arr = Object.freeze([1, 2, 3]);
console.log(arr);
arr[1] = 7;
console.log(arr);
like image 45
Tamas Hegedus Avatar answered Oct 19 '25 18:10

Tamas Hegedus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!