Sub topic 2
Shallow Copies and Shared Nested Data
This chapter assumes you are comfortable with JavaScript objects, arrays and primitive types, object and array spread syntax, and basic use of Map and Set. It also assumes you know from the previous chapter that a variable holding an object holds a reference to it, not the object itself.
A shallow copy is a new container whose top-level slots hold the same values as the original's. Primitives in those slots are copied as values. Objects in those slots are copied as references, so the copy and the original point at the same nested objects. Most built-in ways to "copy" in JavaScript work this way, and most bugs with accidentally shared data come from forgetting that.
The Common Shallow Copy Tools
JavaScript gives you several ways to make shallow copies. They all create a new outer container and copy the top level only.
| Tool | Works on | Notes |
|---|---|---|
| `{ ...obj }` | Objects | Copies own enumerable properties, including symbol keys |
| `Object.assign({}, obj)` | Objects | Same set of properties, but writes with assignment |
| `[...arr]` | Iterables | Turns holes in sparse arrays into `undefined` |
| `arr.slice()` | Arrays | Keeps holes |
| `Array.from(arr)` | Iterables, array-likes | Can take a mapping function |
| `arr.concat()` | Arrays | Rarely used just to copy |
| `new Map(map)` / `new Set(set)` | Maps, Sets | Copies entries; keys and values are still shared |
Every row in this table shares nested objects with the original.
Seeing the Shared Data
Here is the basic failure. The spread creates a new outer object, but user and tags are the same objects in both places.
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']Changing a top-level property of the copy is safe, because that only replaces a slot in the new container:
const original = { user: { name: 'Ada' }, count: 1 };
const shallow = { ...original };
shallow.count = 2; // replaces a slot in the copy
shallow.user = { name: 'Linus' }; // replaces a slot in the copy
console.log(original.count); // 1
console.log(original.user.name); // 'Ada'The rule is simple. Reassigning a property of the copy is isolated. Mutating an object that you reached through the copy is not.
You can confirm sharing with strict equality. Two references are === only when they point to the same object.
const original = { user: { name: 'Ada' }, tags: ['a'] };
const shallow = { ...original };
console.log(shallow === original); // false: new outer object
console.log(shallow.user === original.user); // true: shared nested object
console.log(shallow.tags === original.tags); // true: shared arrayArrays of Objects
Arrays cause the same problem, and it is easy to miss because array copies look more complete. Copying an array of objects gives you a new array full of the same objects.
const todos = [{ text: 'write', done: false }];
const copy = [...todos];
copy[0].done = true;
console.log(todos[0].done); // true
const mapped = todos.map(t => t);
console.log(mapped[0] === todos[0]); // true: map(t => t) is still shallowTo make the items independent, copy each item too. This goes one level deeper and is still shallow below that level:
const todos = [{ text: 'write', done: false, tags: ['work'] }];
const copy = todos.map(t => ({ ...t }));
copy[0].done = true;
console.log(todos[0].done); // false
copy[0].tags.push('urgent');
console.log(todos[0].tags); // ['work', 'urgent']: tags is still sharedSpread Versus Object.assign
Spread and Object.assign copy the same set of properties: the source's own enumerable properties, both string and symbol keyed. Neither copies inherited properties or non-enumerable ones. They differ in how they write to the target.
Object.assign writes each property with ordinary assignment, so it runs setters on the target. Spread in an object literal defines new data properties directly and never calls setters.
const target = {
set name(v) { console.log('setter ran with', v); }
};
Object.assign(target, { name: 'Ada' }); // logs: setter ran with Ada
const literal = {
set name(v) { console.log('this never runs'); },
...{ name: 'Ada' }
};
console.log(Object.getOwnPropertyDescriptor(literal, 'name').value); // 'Ada'Both read the source with ordinary property access, so getters on the source run once and their current results are copied as plain values:
let reads = 0;
const source = { get stamp() { reads += 1; return reads; } };
const a = { ...source };
const b = Object.assign({}, source);
console.log(a.stamp, b.stamp); // 1 2
console.log(Object.getOwnPropertyDescriptor(a, 'stamp').get); // undefinedThe copy holds a frozen snapshot, not a live getter. Later chapters show that structuredClone behaves the same way.
Use Object.assign when you want to mutate an existing target, such as merging into this in a constructor. Use spread when you want a new object.
Prototypes Are Not Copied
A shallow copy of a class instance is a plain object. Spread and Object.assign({}, ...) only look at own properties, so methods and getters defined on the class prototype disappear.
class Temperature {
constructor(celsius) { this.celsius = celsius; }
get fahrenheit() { return this.celsius * 9 / 5 + 32; }
}
const t = new Temperature(20);
const copy = { ...t };
console.log(copy); // { celsius: 20 }
console.log(copy instanceof Temperature); // false
console.log(copy.fahrenheit); // undefinedIf you need the same prototype, create the copy with it explicitly:
class Temperature {
constructor(celsius) { this.celsius = celsius; }
get fahrenheit() { return this.celsius * 9 / 5 + 32; }
}
const t = new Temperature(20);
const copy = Object.assign(Object.create(Object.getPrototypeOf(t)), t);
console.log(copy instanceof Temperature); // true
console.log(copy.fahrenheit); // 68This is still a shallow copy. It only fixes the prototype.
Sparse Arrays and Other Edge Cases
Array copy methods disagree about holes. A hole is an index that has never been assigned, which is different from an index that holds undefined.
const sparse = [1, , 3];
console.log(1 in sparse); // false: index 1 is a hole
console.log(1 in [...sparse]); // true: spread fills it with undefined
console.log(1 in sparse.slice()); // false: slice keeps the hole
console.log(1 in Array.from(sparse)); // trueObject spread also accepts values that are not objects without throwing:
console.log({ ...null }); // {}
console.log({ ...undefined }); // {}
console.log({ ...'hi' }); // { '0': 'h', '1': 'i' }
console.log({ ...[10, 20] }); // { '0': 10, '1': 20 }Array spread is stricter. [...null] throws a TypeError because null is not iterable.
Maps and Sets
The Map and Set constructors accept an iterable, so new Map(existing) makes a new map with the same entries. The entries themselves are not copied.
const settings = new Map([['theme', { dark: true }]]);
const copy = new Map(settings);
copy.set('lang', 'en');
console.log(settings.has('lang')); // false: the map itself is new
copy.get('theme').dark = false;
console.log(settings.get('theme').dark); // false: the value is sharedSpreading a Map into an object literal does not work the way people expect. { ...map } gives {}, because a map stores its entries internally, not as own properties.
Shallow Merges Replace Nested Objects
Spread is often used to combine defaults with user options. Because the merge is shallow, a nested object from the second source replaces the nested object from the first one entirely. It does not merge their keys.
const defaults = { retry: { count: 3, delay: 100 }, verbose: false };
const userOptions = { retry: { count: 5 } };
const merged = { ...defaults, ...userOptions };
console.log(merged.retry); // { count: 5 }: delay is gone
console.log(merged.verbose); // falseIf you want to keep delay, merge that level as well:
const defaults = { retry: { count: 3, delay: 100 }, verbose: false };
const userOptions = { retry: { count: 5 } };
const merged = {
...defaults,
...userOptions,
retry: { ...defaults.retry, ...userOptions.retry }
};
console.log(merged.retry); // { count: 5, delay: 100 }The other half of the same problem is that merged.verbose and the other untouched values come from defaults. If those values were objects, mutating them through merged would change your defaults for every later caller.
Object.freeze Is Shallow Too
Object.freeze stops changes to an object's own properties, but it does not follow references. Nested objects stay mutable.
'use strict';
const config = Object.freeze({ db: { host: 'localhost' } });
try {
config.db = {};
} catch (err) {
console.log(err.name); // 'TypeError'
}
config.db.host = 'example.com';
console.log(config.db.host); // 'example.com'A frozen object that you copy with spread also gives you an unfrozen copy, because spread creates ordinary writable properties.
When Shallow Copies Are the Right Tool
Shared nested data is not always a bug. Immutable update patterns, used in React state and Redux reducers, depend on it. You copy only the path you change and share everything else. This is called structural sharing, and it keeps updates cheap and lets code detect changes with ===.
const state = {
user: { name: 'Ada', address: { city: 'London' } },
tags: ['a', 'b']
};
const next = {
...state,
user: {
...state.user,
address: { ...state.user.address, city: 'Paris' }
}
};
console.log(state.user.address.city); // 'London'
console.log(next.user.address.city); // 'Paris'
console.log(next.tags === state.tags); // true: shared, unchanged
console.log(next.user === state.user); // false: changed path was copiedThis works only if nobody mutates the shared parts. Once some code mutates a nested object in place, every state that shares it changes too.
Spreading every level by hand becomes tedious and fragile for deep or irregular data. The next chapter looks at the oldest workaround, the JSON round-trip, and what it breaks.
Common Errors
- Assuming
[...arr]orarr.map(x => x)copies the objects inside the array. - Spreading defaults and options and expecting nested keys to merge.
- Spreading a
Map,SetorDateinto{}and getting an empty object. - Expecting
{ ...instance }to keep class methods and getters. - Trusting
Object.freezeto protect nested data.
Exercise
Given const a = { list: [1, 2], n: 1 }; const b = { ...a }; b.n = 5; b.list.push(3); b.list = [9]; what are a.n and a.list afterwards, and why?
Show answer
a.n is 1 and a.list is [1, 2, 3]. Setting b.n replaces a slot in the new outer object, so a is unaffected. b.list.push(3) mutates the array that a and b still share, so a sees the 3. The later b.list = [9] only points b's slot at a new array and leaves a.list alone.
Exercise
const base = { headers: { accept: 'json' } }; const req = { ...base }; req.headers.auth = 'token'; Write a version of the copy line that stops auth from appearing on base.headers, and say whether your fix would still be enough if headers contained a nested object.
Show answer
Copy the nested level too: const req = { ...base, headers: { ...base.headers } }; Now req.headers is a new object, so adding auth does not touch base.headers. It would not be enough if headers held a nested object, because that inner object would still be shared. You would have to spread that level as well or make a deep copy.
Exercise
Why does Object.assign(target, { name: 'Ada' }) log a message when target has a setter for name, while { set name(v) { console.log(v); }, ...{ name: 'Ada' } } logs nothing?
Show answer
Object.assign writes each property with ordinary assignment, which calls a setter on the target. Spread in an object literal defines data properties directly, so it replaces the accessor with a plain data property holding 'Ada' and never calls the setter.