How to keep arrays immutable with the spread operator

Overview

The spread operator allows expressions to be expanded in places where multiple arguments, elements, or variables are expected.

Array.push()

Pushing to an array is excellent, but doing so mutates the original array. This can have unforeseen side effects if you reuse the array often.

const arr = [1, 2];
arr.push(3);
console.log(arr); // arr => [1,2,3]

Spread operator

The original array remains intact if you copy the array with the spread operator and append it to the new one. Doing so supports immutability and prevents unforeseen side-effects.

const arr = [1, 2];
const newArr = [...arr, 3];
console.log(arr);
console.log(newArr);
// arr => [1,2]
// newArr => [1,2,3]

Free Resources