JavaScript hands objects around by reference instead of by value. That single rule explains why a function can quietly change an object that you did not know it had touched, and it also explains why a copy that looks right on the surface still shares its insides with the original.
The previous lesson in this module covered "Adding, Updating and Removing Object Keys", and the next lesson in this module is about "Object.keys, entries and Iteration Patterns".
Why do two variables change the same object?
Assigning one variable to another does not create a second object. It creates a second name for the first one.
const settings = { theme: 'dark' };
const alias = settings;
alias.theme = 'light';
console.log(settings.theme); // light
console.log(settings === alias); // true
The two names are two handles on the same object, which is why the strict equality check says true and why changing one changes the other. Exactly the same thing happens when an object is passed into a function. The parameter is simply another name for the object that the caller holds, so any change that the function makes is visible to the caller afterwards.
What does a shallow copy actually copy?
A shallow copy creates a new object at the top level, but it keeps the same references to the values inside it. That is one level of copying, and no more than that.
const original = { name: 'Ada', prefs: { fontSize: 14 } };
const shallow = { ...original };
shallow.name = 'Grace'; // the copy owns this key
shallow.prefs.fontSize = 18; // both objects share one prefs object
console.log(original.name); // Ada
console.log(original.prefs.fontSize); // 18
Look at the two results. Changing shallow.name left the original alone, because a string is copied by value. Changing shallow.prefs.fontSize did reach the original, because original.prefs and shallow.prefs point at the same nested object. A shallow copy is safe for flat data, and it becomes unsafe the moment one of the values is itself an object.
One habit is worth adopting early. When data arrives from outside your program, such as a fetch response, a form value, or a value that you parsed out of local storage, treat it as read-only. Freeze it with Object.freeze, or copy it with structuredClone before you start changing it. That turns a subtle reference bug into an immediate and obvious error at the exact point where the change was attempted.
How do I make a genuine deep copy?
structuredClone() is built into the platform, and it copies the entire structure. Nested objects, nested arrays, maps, sets, and dates are all handled for you.
const original = { name: 'Ada', prefs: { fontSize: 14 } };
const deep = structuredClone(original);
deep.prefs.fontSize = 18;
console.log(original.prefs.fontSize); // 14
console.log(deep.prefs.fontSize); // 18
Now the two objects are genuinely independent. structuredClone also handles the things that a hand-written recursive copy usually gets wrong. It keeps Date objects, maps, and sets as they are. It follows cyclic references instead of looping forever. And it refuses to copy functions, which raises a DataCloneError instead of quietly dropping them.
When you only need to change a couple of top-level fields, building a new object with the spread syntax is often better than cloning the whole thing. It states exactly what you are keeping and what you are replacing, and it costs nothing. Reach for structuredClone when the structure is deep, when you do not know how deep it goes, or when the object came from outside your program and you need a genuinely private version of it.
What does a JSON round trip lose?
The older trick for cloning an object is to turn it into JSON text and then parse that text back again. It works for plain data, and it quietly loses everything that JSON cannot represent.
const original = {
when: new Date(0),
tags: ['a'],
missing: undefined,
set: new Set([1]),
};
const snapshot = JSON.parse(JSON.stringify(original));
console.log(snapshot.when); // '1970-01-01T00:00:00.000Z'
console.log(snapshot.tags); // [ 'a' ]
console.log('missing' in snapshot); // false
console.log(snapshot.set); // {}
A Date turns into an ISO string, the property with the value undefined disappears entirely, and a Set becomes an empty object because JSON has no way to describe one. The JSON round trip remains the right tool when the goal is moving data between systems, and it is the wrong tool when the goal is cloning an object inside your own program.
What happens to objects stored inside arrays?
The same rules apply, one level deeper. Spreading an array gives you a new array whose items are the very same objects, so changing an item inside the copy also changes the item in the original.
const team = [{ name: 'Ada' }, { name: 'Linus' }];
const copied = [...team];
copied[0].name = 'Grace';
console.log(team[0].name); // Grace
const deep = structuredClone(team);
deep[0].name = 'Chen';
console.log(team[0].name, deep[0].name); // Grace Chen
Read the last line carefully. The deep copy was taken after the first change, so it inherited Grace before that value was set to Chen. The point of the example is that the deep copy and the original no longer share anything, because changing deep[0] leaves team[0] alone.
How do you compare two objects?
Two different objects are never equal under ===, because === compares references for objects. Comparing data therefore means comparing the contents.
const original = { name: 'Ada' };
const copy = { ...original };
console.log(original === copy); // false
console.log(JSON.stringify(original) === JSON.stringify(copy)); // true
The first line is the rule itself. The second line is the quick content check, and it works because JSON.stringify produces the same text for two objects that have the same keys in the same order. Treat it as a debugging aid rather than as a test. The order of the keys changes the output, and any property whose value is undefined is skipped entirely. For proper comparisons, Node's test runner ships deep equality assertions, and the testing module later in this tutorial shows you how to use them.
Which copy technique should I use?
| Technique | Copies nested objects? | Keeps Date, Map, Set? | Note |
|---|---|---|---|
{ ...obj } | No | Yes, same references | One level only |
Object.assign({}, obj) | No | Yes, same references | Same depth as spread |
structuredClone(obj) | Yes | Yes | Throws on functions |
JSON.parse(JSON.stringify(obj)) | Yes | No | Loses Dates, Sets and undefined |
Try it yourself: write a file called copies.js and create const original = { title: 'Notes', tags: ['js'], meta: { pinned: false } };. Make a shallow copy with the spread syntax, push 'web' onto copy.tags, and then print original.tags to watch it change. Now make a deep copy with structuredClone, push 'web' onto deep.tags, set deep.meta.pinned to true, and then print original.tags and original.meta.pinned to watch them stay exactly where they were. Finish by printing whether original === copy and whether original === deep, and by running JSON.stringify over an object that contains a Date so that you can see the text it produces.