🍒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.

const arr = [1, 2, 3];

const copy = [...arr];

console.log(copy); // [1, 2, 3]

The Array.prototype.slice() method: This method creates a new array that includes a copy of a portion of an existing array.

const arr = [1, 2, 3];

const copy = arr.slice();

console.log(copy); // [1, 2, 3]

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.

const obj = { name: 'John', age: 30 };

const copy = Object.assign({}, obj);

console.log(copy); // { name: 'John', age: 30 }

The spread operator (...): This operator can also be used to create a new object that includes the properties of an existing object.

const obj = { name: 'John', age: 30 };

const copy = { ...obj };

console.log(copy); // { name: 'John', age: 30 }

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