Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
reduce
readability
performance
communitycreator

How to keep arrays immutable with the spread operator

Non Stop Learning...

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]

RELATED TAGS

javascript
reduce
readability
performance
communitycreator

CONTRIBUTOR

Non Stop Learning...
RELATED COURSES

View all Courses

Keep Exploring