JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 8: Objects and Structured DataLesson 39 of 150About 45 minutes

Lesson 39: Object copying and reference behavior

01Opening question

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.

You need: Lesson 38: Nested objects and arrays

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.

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.

Open the full glossary

06Visual learning object

Reference versus value laboratory. Step through assignments and copies and see which variables share an object.

Loading the interactive object…

Open the full Reference versus value laboratory page with its guided experiment.

07Examples

ex-039-01Primitives are copied Browser-executable JavaScript

Changing y does not change x.

let x = 10;
let y = x;
y = 20;
console.log(x, y);
let s = "hi";
let t = s;
t += "!";
console.log(s, t);
Sample input
None
Expected output
10 20 hi hi!
Common mistake
Expecting y = x to link the two variables.
Try this
Try the same with booleans.
Source
examples/ex-039-01-primitives-copy.js (repository pending publication)

ex-039-02Objects are shared Browser-executable JavaScript

Two names, one object.

const original = { name: "Mug", price: 8 };
const alias = original;
alias.price = 6;
console.log(original.price);
console.log(alias === original);
Sample input
None
Expected output
6 true
Common mistake
Thinking alias is a copy.
Try this
Make alias a real copy with spread.
Source
examples/ex-039-02-shared-reference.js (repository pending publication)

ex-039-03Shallow copies share nested objects Browser-executable JavaScript

Spread copies the outer level only.

const user = { name: "Ada", prefs: { theme: "light" } };
const copy = { ...user };
copy.name = "Grace";
copy.prefs.theme = "dark";
console.log(user.name, user.prefs.theme);
Sample input
None
Expected output
Ada dark
Common mistake
Expecting spread to copy nested objects.
Try this
Copy prefs as well: { ...user, prefs: { ...user.prefs } }.
Source
examples/ex-039-03-shallow-copy.js (repository pending publication)

ex-039-04Deep copies and equality Browser-executable JavaScript

structuredClone copies everything; === compares references.

const cart = { items: [{ sku: "A", qty: 1 }] };
const draft = structuredClone(cart);
draft.items[0].qty = 3;
console.log(cart.items[0].qty, draft.items[0].qty);
console.log({ a: 1 } === { a: 1 });
console.log(JSON.stringify({ a: 1 }) === JSON.stringify({ a: 1 }));
Sample input
None
Expected output
1 3 false true
Common mistake
Comparing objects with === and expecting a content comparison.
Try this
Add a nested object to cart and check it is copied.
Source
examples/ex-039-04-deep-copy-equality.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Copy before changing

Replace a shared reference with a copy.

const prices = [10, 20, 30];
const discounted = prices;
for (let i = 0; i < discounted.length; i++) discounted[i] = discounted[i] * 0.5;
console.log(prices, discounted);

Immutable nested update

Copy only the path that changes.

const state = { user: { name: "Ada", theme: "light" }, cart: [1, 2] };
// TODO: create next with user.theme = "dark" without changing state
console.log(state.user.theme, next.user.theme, next.cart === state.cart);

Draft order editor

Edit a deep copy and compare by content.

const saved = { id: 5, lines: [{ sku: "M1", qty: 1 }, { sku: "T2", qty: 2 }] };

09Prediction

Commit to an answer first, then run the real code to compare.

const a = [{ n: 1 }];
const b = [...a];
b[0].n = 2;
b.push({ n: 3 });
console.log(a.length, a[0].n);

What is printed?

10Debugging investigation

Every invoice ends up with the same customer

Two invoices are created from one template, but after filling the second, both show Grace as the customer.

const template = { number: 0, customer: { name: "" } };
function newInvoice(n, name) {
  const inv = { ...template, number: n };
  inv.customer.name = name;
  return inv;
}
const inv1 = newInvoice(1, "Ada");
const inv2 = newInvoice(2, "Grace");
console.log(inv1.customer.name, inv2.customer.name);

More cases in the Debugging Detective Laboratory

11Practical scenario

Undo in an editor

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?

const copy = { ...user };
copy.address.city = "Paris";
  • Spread is a deep copy
  • Spread is shallow, so address is shared
  • address is a string
  • const prevents copying

5. Which makes a deep copy of plain data?

  • =
  • { ...obj }
  • structuredClone(obj)
  • Object.keys(obj)

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.
  • Spread makes a shallow copy.
  • structuredClone makes a deep copy.
  • === compares references, not contents.

16AI learning prompts

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 explanation references 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 prediction references 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.
Debugging references 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 generation references 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 review references 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.