Immutable Array Updates: Adding Elements
You'll learn how to add items to an array without mutating the original, keeping your data structures safe and predictable.
Why This Matters
When working with immutable data, you can't use methods like push() or unshift() because they change the original array. Instead, you need techniques that create a new array with the added elements.
Adding to the End
The spread operator is your best friend here:
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
// numbers stays [1, 2, 3]
// newNumbers is [1, 2, 3, 4, 5]
Alternatively, use concat():
const colors = ['red', 'blue'];
const moreColors = colors.concat('green', 'yellow');
// colors unchanged
Adding to the Beginning
Spread works here too—just place new items first:
const items = ['b', 'c'];
const withPrefix = ['a', ...items];
// ['a', 'b', 'c']
You can also use concat() in reverse:
const letters = ['x', 'y'];
const prefixed = ['w'].concat(letters);
// ['w', 'x', 'y']
Adding in the Middle
Combine spread with array slicing:
const list = [1, 2, 5, 6];
const insertAt2 = [...list.slice(0, 2), 3, 4, ...list.slice(2)];
// [1, 2, 3, 4, 5, 6]
Think of it like cutting a piece of paper: you copy everything before the insertion point, add your new items, then copy everything after.
Key Takeaway: Use spread syntax or concat() to add elements immutably—they return new arrays while leaving originals untouched, making your code predictable and easier to debug.