Creating Immutable Arrays

There are two main ways to create immutable arrays:

  • Using array concat method

  • Using spread operator


Using array concat method:

Suppose, we've a list of numbers:

const numbers = [1, 2, 3, 4];


Then to add a new number to the array we can use the array concat method as shown below:

const numbers = [1, 2, 3, 4];
const newNumbers = numbers.concat(5);

console.log(numbers); // [1, 2, 3, 4]
console.log(newNumbers); // [1, 2, 3, 4, 5]


As you can see, the array concat method returns a new array instead of changing the original array.

Note that, the array push method changes the original array so we can't use the array push method to add a new element to the array.

Using spread operator:

Take a look at the below code:

const numbers = [1, 2, 3, 4];
const newNumbers = [...numbers, 5];

console.log(numbers); // [1, 2, 3, 4]
console.log(newNumbers); // [1, 2, 3, 4, 5]


As you can see, using the spread operator also produces a new array without changing the original array.

You can use either the array concat method or spread operator to create an immutable array. 

We will be using the spread operator for creating a new array as it's easy to understand and is a preferred way of creating new arrays when working in React.