Sub topic 2
Transforming Arrays Without Mutation
This chapter assumes you know spread syntax, arrow functions, and strict mode, and that you understand objects are shared by reference.
Add, Remove, and Update Without Mutation
Methods like push, splice, and sort change the array in place. Any other code holding the same array sees the change. The fix is to build a new array each time. Use spread to add an item, filter to remove one, and map to update one.
const todos = [
{ id: 1, text: 'Write', done: false },
{ id: 2, text: 'Review', done: false }
];
const added = [...todos, { id: 3, text: 'Ship', done: false }];
const removed = todos.filter(t => t.id !== 1);
const toggled = todos.map(t => (t.id === 2 ? { ...t, done: !t.done } : t));
console.log(todos.length); // 2, the original array is unchanged
console.log(toggled[0] === todos[0]); // true, unchanged items are reusedA common mistake is returning t after setting t.done = true inside map. The array is new, but the item has been mutated in place.
toSorted, toReversed, toSpliced, and with
ES2023 added copying versions of the mutating methods. Each one returns a new array:
const nums = [3, 1, 2];
const sorted = nums.toSorted(); // [1, 2, 3]
const reversed = nums.toReversed(); // [2, 1, 3]
const spliced = nums.toSpliced(1, 1); // [3, 2]
const replaced = nums.with(0, 9); // [9, 1, 2]
console.log(nums); // [3, 1, 2], the original is untouchedUpdating Nested Data Immutably
Spread copies only one level. To change a deeply nested value, copy every object on the path to it and reuse everything else:
const state = {
user: { name: 'Ada', address: { city: 'London' } },
settings: { theme: 'dark' }
};
const next = {
...state,
user: {
...state.user,
address: { ...state.user.address, city: 'Paris' }
}
};
console.log(state.user.address.city); // 'London'
console.log(next.settings === state.settings); // true, the unchanged branch is shared
console.log(next.user === state.user); // false, the changed path was copiedEnforcing Immutability with Object.freeze
Object.freeze blocks changes to an object's own properties. It is shallow, so nested objects need to be frozen recursively:
'use strict';
function deepFreeze(obj) {
for (const value of Object.values(obj)) {
if (value !== null && typeof value === 'object') {
deepFreeze(value);
}
}
return Object.freeze(obj);
}
const config = deepFreeze({ api: { retries: 3 } });
console.log(Object.isFrozen(config.api)); // true
// config.api.retries = 5; // TypeError in strict modeExercise
Given const list = [5, 2, 8], write one expression that returns a new array sorted in ascending order with the first element replaced by 0, leaving list unchanged.
Show answer
list.toSorted((a, b) => a - b).with(0, 0) returns [0, 5, 8]. Both methods return new arrays, so list stays [5, 2, 8].
Exercise
After const s = Object.freeze({ tags: ['a'] }), does s.tags.push('b') succeed?
Show answer
Yes. Object.freeze is shallow, so the nested array is still mutable. Use a recursive deep freeze to block this.