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?
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).
You could use Object.freeze
for that.
const arr = Object.freeze([1, 2, 3]);
console.log(arr);
arr[1] = 7;
console.log(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With