Objects · Lesson 24 of 45
Copies and references
Why changing a copy sometimes changes the original.
8 minutes3 games
Simple values (numbers, strings, booleans) are copied by value: each variable gets its own copy. Objects and arrays are copied by reference: both variables point at the same object in memory.
Step by step1 / 7
- ▶const a = { score: 10 }
- 2const b = a
- 3b.score = 99
- 4console.log(a.score)
- 5const c = { ...a }
- 6c.score = 5
- 7console.log(a.score, c.score)
Variables
| a | → obj1 { score: 10 } |
Output
…
| Method | Kind | Notes |
|---|---|---|
| not a copy | the same object |
| shallow copy | nested objects stay shared |
| deep copy | everything is new |
JavaScript
const user = { name: "Ali", address: { city: "Cairo" } }
const shallow = { ...user }
shallow.address.city = "Giza"
console.log(user.address.city) // Giza: nested object is shared!
const deep = structuredClone(user)
deep.address.city = "Aswan"
console.log(user.address.city) // still GizaWhat's the output?
const list = [1, 2] const copy = list copy.push(3) console.log(list.length)
What will this code print?
Quick question
What is [1] === [1]?
Exercise
Copy original, push 4 into the copy, and print the original's length (it must stay 3).
Expected output: 3
JavaScript
const original = [1, 2, 3]
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.