×

javascript · level 3 · unit 4 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.