Sub topic 1
Why Copying Objects Is Tricky: Values and References
Prerequisites
This chapter assumes you know JavaScript objects, arrays and primitive types, and that you can use spread syntax, Map, Set and Date. You also need a browser console or Node.js 17 or later to run the examples.
Values and References
Primitives such as numbers, strings and booleans are copied by value. When you assign one to a new variable, you get an independent copy. Objects and arrays work differently. A variable holds a reference to the object, so const b = a copies only that reference. After the assignment, a and b point to the same object, and a change made through one is visible through the other.
Shallow Copies and Shared Nested Data
Spread syntax ({ ...obj }) and Object.assign create a new top-level object. Any nested objects or arrays inside it are still shared with the original:
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']A common bug is to assume spread syntax protects nested state. It protects only the first level.
The JSON Round-Trip and What It Breaks
JSON.parse(JSON.stringify(value)) makes a deep copy, but only of data that JSON can represent:
const data = { when: new Date(0), missing: undefined, ratio: NaN, ids: new Set([1, 2]) };
const copy = JSON.parse(JSON.stringify(data));
console.log(copy);
// { when: '1970-01-01T00:00:00.000Z', ratio: null, ids: {} }In this example, the Date becomes a string, the undefined property disappears, NaN becomes null, and the Set becomes an empty object. A circular reference makes JSON.stringify throw a TypeError.
Making Deep Copies with structuredClone
structuredClone(value) is a built-in global function that copies a value and everything nested inside it. It keeps built-in types such as Date, Map and Set:
const original = {
when: new Date(0),
ids: new Set([1, 2]),
meta: new Map([['k', { v: 1 }]])
};
const copy = structuredClone(original);
console.log(copy.when instanceof Date); // true
console.log(copy.ids.has(2)); // true
console.log(copy.meta.get('k') === original.meta.get('k')); // false
copy.meta.get('k').v = 99;
console.log(original.meta.get('k').v); // 1Exercise
You copy { settings: { dark: true } } with spread syntax, then set copy.settings.dark = false. What is original.settings.dark, and which function call would keep it true?
Show answer
It is false, because spread syntax shares the nested settings object between the original and the copy. Copying with structuredClone(original) creates a new settings object, so original.settings.dark stays true.
Exercise
Name two ways a JSON round-trip changes { d: new Date(0), n: NaN }.
Show answer
The Date becomes an ISO string, and NaN becomes null.