🍒Creating new arrays or objects
It is not possible to directly make an array or object immutable in JavaScript. However, you can use specific methods to create a new copy of an array or object, which will preserve the value of the original variable.
To create a new copy of an array, you can use the following methods:
The spread operator (
...
): This operator allows you to create a new array that includes the values of an existing array.
The Array.prototype.slice()
method: This method creates a new array that includes a copy of a portion of an existing array.
To create a new copy of an object, you can use the following methods:
The
Object.assign()
method: This method creates a new object and copies the properties of an existing object into it.
The spread operator (...
): This operator can also be used to create a new object that includes the properties of an existing object.
Using these methods to create a new copy of an array or object allows you to preserve the value of the original variable, while still being able to modify the new copy if needed. This can be useful if you want to keep track of previous states of an array or object, or if you want to avoid unintended modifications to the original data.
Last updated