Copies and references
JavaScript · Unit 15: Immutability
- Full plan
- JavaScript
- 10 exercises
You already know = doesn't copy an object: it gives it a second name. And that { ...obj } does build a new one, but only the first level.
That's called a shallow copy: if there's another object inside, the copy and the original share that inner object.
const a = { n: 1, sub: { m: 2 } };
const b = { ...a };
b.n = 9;
b.sub.m = 9;
console.log(a.n, a.sub.m);Prints
1 9
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
The order gets copied and two things change. What does it print?
2. Multiple choice
userholdsnameandaddr, andaddris another object. What does{ ...user }create?3. Complete the code
Fill in the blank so bumping the copy's points doesn't bump Leo's.
4. Complete the code
Fill in the blank so the copy carries new objects, not the same ones.
5. Predict the output
Two copies of the same list, made in different ways. What does it print?
6. Find the bug
rshould be a copy ofbthat stands on its own: signing Leo up inrshould leaveb's crew with Ana alone. Which line has the error?7. Predict the output
The record is copied with the JSON round trip. What does it print?
8. Multiple choice
When does copying with
JSON.parse(JSON.stringify(x))not work?9. Put the lines in order
Put the program in order: it copies the recipe deeply and adds garlic to the copy only.
10. Predict the output
The function hands out a bonus. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.