Sub topic 2
Shallow Copies and Shared Nested Data
This chapter assumes you know JavaScript objects, arrays and primitive types, and that you can read object and array spread syntax. It also builds on the previous chapter's idea that a variable holding an object stores a reference to that object, not the object itself.
What a shallow copy does
A shallow copy is a new object whose top-level properties hold the same values as the original's. If a property holds a primitive, such as a string or a number, the copy gets its own value. If a property holds an object or array, the copy gets the same reference, so both objects point at one shared nested value.
JavaScript gives you several ways to make shallow copies:
| Tool | Works on | Example |
|---|---|---|
| Object spread | Objects | `{ ...obj }` |
| `Object.assign` | Objects | `Object.assign({}, obj)` |
| Array spread | Arrays and other iterables | `[...arr]` |
| `Array.prototype.slice` | Arrays | `arr.slice()` |
| `Array.from` | Arrays and iterables | `Array.from(arr)` |
All five copy only one level deep.
Seeing the shared data
const original = { user: { name: 'Ada' }, tags: ['a'] };
const shallow = { ...original };
shallow.user.name = 'Grace';
shallow.tags.push('b');
console.log(original.user.name); // 'Grace'
console.log(original.tags); // ['a', 'b']shallow is a different object from original, so shallow === original is false. But shallow.user and original.user are the same object, and so are the two tags arrays. Changing either one through the copy also changes it in the original.
What is independent
Changes at the top level of the copy stay in the copy. Reassigning a property replaces the reference in one object only:
const original = { user: { name: 'Ada' }, count: 1 };
const shallow = { ...original };
shallow.count = 2; // primitive at the top level
shallow.user = { name: 'Grace' }; // new object replaces the reference
console.log(original.count); // 1
console.log(original.user.name); // 'Ada'Remember the rule this way: assigning to a property of the copy is safe, but changing an object reached through the copy is not.
Arrays of objects
Copying an array has the same effect on its elements. If the elements are objects, the new array holds the same objects:
const todos = [{ text: 'write', done: false }];
const copy = todos.slice();
copy[0].done = true;
copy.push({ text: 'test', done: false });
console.log(todos[0].done); // true (shared element was changed)
console.log(todos.length); // 1 (push only changed the copy)The common mistake and the usual fix
This bug often shows up in state updates, such as React state or Redux reducers, where code that looks like it makes a copy still changes the previous state:
function renameBroken(state, name) {
const next = { ...state };
next.user.name = name; // changes state.user too
return next;
}Whenever you change a nested value, copy each level along the path to it:
function rename(state, name) {
return { ...state, user: { ...state.user, name } };
}
const before = { user: { name: 'Ada', role: 'admin' }, tags: ['a'] };
const after = rename(before, 'Grace');
console.log(before.user.name); // 'Ada'
console.log(after.user.name); // 'Grace'
console.log(after.tags === before.tags); // true (untouched data is still shared)Other details of shallow copies
- Spread and
Object.assigncopy only own enumerable properties. Inherited properties and the prototype are not copied, so spreading a class instance gives you a plain object. Object.assignruns setters on the target and reads getters on the source. Spread defines new properties and does not run setters.- Both copy symbol-keyed own enumerable properties.
Exercise
Given const a = { list: [1, 2], n: 0 }; const b = Object.assign({}, a); b.n = 5; b.list.push(3); b.list = [9];, what are a.n and a.list afterward?
Show answer
a.n is 0, because n is a primitive at the top level. a.list is [1, 2, 3]: push changed the shared array before b.list was reassigned, and that reassignment only replaced the reference in b.
Exercise
Write an update that sets state.settings.theme.dark to true without changing state or any object inside it.
Show answer
const next = { ...state, settings: { ...state.settings, theme: { ...state.settings.theme, dark: true } } }; copies each level on the path to dark and shares everything else.