Updating without mutating
JavaScript · Unit 15: Immutability
- Full plan
- JavaScript
- 10 exercises
So how do you change something without changing it? You don't: you build a fresh version out of what was already there, with the change on top.
That's the whole idea behind { ...old, change }, and now you know what it's really for.
const t = { txt: "bread", done: false };
const t2 = { ...t, done: true };
console.log(t.done, t2.done);Prints
false true
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 function marks the task as done. What does it print?
2. Complete the code
Fill in the blank to build a product priced at 66, without changing the one that already exists.
3. Complete the code
Fill in the blank to leave the 20 out without removing it from the original list.
4. Predict the output
A candle is added and then the mug is taken out. What does it print?
5. Complete the code
Fill in the blank so task 1 comes out ticked in the new list and unticked in the old one.
6. Find the bug
discountshould give back a cheaper product without changing the price of the one it receives, so this should print 60 and 50. Which line has the error?7. Multiple choice
Why does a function that receives an object usually return a new one instead of changing it?
8. Put the lines in order
Put the program in order: it builds a new list with the task ticked, using
mapand an arrow that returns an object.9. Find the case that fails
mark(ts, i)returns a new list with the task at positioniticked, without touching the one it receives; if that position doesn't exist, it returns the list as it is. Which call does it fail on?10. Predict the output
The fresh version is built with the three dots. 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.