Following meaning

Lesson 12 Data flow

5 min read · JavaScript · Quiz

follow one value, mutation versus copy, aliasing

What you'll learn

  • Tell a new value from a second name for the same one
  • Spot shallow copies and in-place changes that surprise the caller
  • Judge whether an AI change from copy to mutation is safe

The sneakiest bugs aren't in a calculation. They're in a value that changed somewhere else, because two names pointed at the same thing.

The idea

To follow data, pick one value and ask at every line: is this a new value, or the same one under another name? Objects and arrays are shared, not copied. const b = a gives you a second name for the same object, and changing one changes both.

Spreading with { ...order } makes a shallow copy: a new outer object, but the same inner objects. Some methods change their input in place, like sort and push. Others return something new. Know which is which.

discount.js
1function applyDiscount(order, pct) {2  const updated = { ...order };3  updated.total = order.total * (1 - pct / 100);4  updated.items.push({ sku: "GIFT", qty: 1, price: 0 });5  return updated;6}
  1. Line 2 A copy, so far so good. But { ...order } is shallow: updated.items is the very same array as order.items.
  2. Line 3 Safe: assigning total changes only the new object. The original keeps its old total.
  3. Line 4 The bug: push changes the shared array, so the caller's original order gets the gift item too.

Take away

  • Ask of every value: new, or the same one under another name?
  • A spread or a copy of an object is shallow: inner objects are still shared.
  • Know which methods change their input in place, like sort and push.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.