javascript · level 3 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Pure functions return new data instead of changing old data.
A only reads its arguments and returns a result. It never mutates what it was given or anything outside it. Same input, same output, every time, which makes it a joy to test.
Anything else a function does is a . To update without mutating, build a copy with spread: { ...cart, owner: "Al" } copies the top level and changes one property. Spread is shallow, so for nested data use structuredClone, which makes a .
const cart = { owner: "Jo", items: ["pen"] };
function addItem(oldCart, item) {
return { ...oldCart, items: [...oldCart.items, item] };
}
const newCart = addItem(cart, "ink");
console.log(cart.items, newCart.items);
const backup = structuredClone(newCart);
backup.items.push("pad");
console.log(newCart.items, backup.items); Undo buttons and history features rely on this: every old version is still there, untouched.
guess first
A discount with a side effect. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function withDiscount(order) {
order.total = order.total * 0.5;
return order;
}
const original = { id: 7, total: 40 };
const sale = withDiscount(original);
console.log(original.total, sale.total, sale === original);
your turn
Your turn. Level up without mutating.
The player is frozen, so mutating it would throw. Fill in a new level that is one more than the old one, using spread to copy the rest.
fix it
The copy changed the original. Can you fix it?
copyis a new object, so why didweek.taskschange as well?- Spread is shallow. The copy holds the very same
tasksarray as the original. - Make a deep copy instead:
const copy = structuredClone(plan);.
nailed it
you change data without breaking it. :D
- Pure functions return new data and change nothing else.
- Spread makes shallow copies; nested data is still shared.
structuredClonemakes a deep copy of nested data.
new words in your collection
- pure function
- side effect
- deep copy
This lesson isn’t saved. A free account remembers every lesson you finish.