You copy a cart to try a discount, change the copy, and the real cart changes too. Why?
Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.
02Start with working code
b = a copies the reference, not the object. Spread creates a new object.
const a = { qty: 1 };
const b = a;
b.qty = 5;
console.log(a.qty);
const c = { ...a };
c.qty = 9;
console.log(a.qty, c.qty);
03Objective and prerequisites
Learning objective: Explain value versus reference, predict when two variables share one object, make shallow copies with spread and deep copies with structuredClone, and compare objects correctly.
Skills practised: Objects, References and copying.
04Explanation
Primitive values (numbers, strings, booleans) are copied: let y = x; gives y its own copy.
Objects and arrays are shared by reference: const b = a; makes b point to the same object. Changing b changes what a sees.
A shallow copy makes a new outer object: { ...obj } or [...arr]. Nested objects inside are still shared.
structuredClone(obj) makes a deep copy: every nested object and array is copied too.
Function arguments are passed by value, but for objects the value is the reference, so a function can mutate a caller's object. Document or avoid that.
structuredClone handles Dates, Maps, Sets and cycles but throws on functions and DOM nodes; JSON.parse(JSON.stringify(x)) loses Dates, undefined and Infinity.
=== on objects compares references: two separate objects with the same contents are not equal. Compare the relevant fields, or a stable serialisation, when you need content equality.
Immutable updates copy only the path that changes: { ...state, user: { ...state.user, name } }. This is the basis of React and Redux state updates.
05Definitions
Reference
A pointer to an object in memory; copying it does not copy the object.
Shallow copy
A new top-level object whose nested objects are still shared.
Deep copy
A copy in which every nested object is also copied.
structuredClone
A built-in function that makes a deep copy of data.
Immutable update
Creating a changed copy instead of modifying the original.
A drawing app keeps a history of states for undo. Each change creates a new state object instead of mutating the current one, so every entry in the history keeps its own values.
const history = [{ shapes: [] }];
const cur = history.at(-1);
history.push({ ...cur, shapes: [...cur.shapes, "circle"] });
console.log(history[0].shapes.length, history[1].shapes.length);
12Knowledge check
1. What is printed?
const a = { v: 1 };
const b = a;
b.v = 2;
console.log(a.v);
1
2
2. What is printed?
const a = { v: 1 };
const c = { ...a };
c.v = 2;
console.log(a.v);
1
2
3. What is printed?
console.log([1] === [1]);
true
false
4. Why does editing the copy change the original's address?
6. A function must not change its caller's array. Which is safest?
Sort the parameter directly
Copy it first: const list = [...input]
Use var
Return nothing
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
Copy before changing: Original kept
Immutable nested update: Prints light dark true; New user object
Draft order editor: Prints 1 3 true; Fresh draft has no changes; Draft is a deep copy
ex-039-01: output matches the documented expected output
ex-039-02: output matches the documented expected output
ex-039-03: output matches the documented expected output
ex-039-04: output matches the documented expected output
The lesson lives in the companion repository at curriculum/level-02-core-development/module-08-objects-and-structured-data/lesson-039-object-copying-and-reference-behavior/. Every example on this page is generated from those files.
The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.
15Summary and next steps
Primitives are copied; objects are shared by reference.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationreferences and copying
Context: I am learning references and copying in JavaScript.
Task: Explain value vs reference, shallow vs deep copies and === on objects, with diagrams in text.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code predictionreferences and copying drill
Context: I have practised references and copying.
Task: Give me six snippets with assignments and copies and ask which values change.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debuggingreferences and copying bug
Context: Editing my copy also changes the original object.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generationreferences and copying practice
Context: I finished the references and copying exercises.
Task: Create three exercises on immutable updates of nested state.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code reviewreferences and copying review
Context: Here is my code that uses references and copying.
Task: Review my code for accidental shared references and suggest copies where needed.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.