Memory Rope — JavaScript

Guess the final values on Bu Yanti's washing line: 18 levels of references vs values, aliasing, shallow copies and object mutation.

What you learn in this game

JavaScript has two kinds of values. Primitives (number, string, boolean, null) are copied by value: b = a gives b a copy in a basket of its own. Objects & arrays are shared by reference: b = a ties b's rope to the same basket. In this game, run the code in your head, then guess each expression's final value. The trick: track whose ropes lead to the same basket.

When you write let b = a and a is an object, b doesn't get a new object: b's rope is tied to the same basket. Two names, two ropes, one basket on the heap. So b.x = 9 changes that basket, and a.x becomes 9 too. This is the most common aliasing bug.

The spread operator { ...a } makes a new basket and copies a's key and value pairs into it. Now a and b are two different baskets, so b.x = 9 doesn't touch a. This is how you make a shallow copy so changes don't leak.

The biggest trap: { ...a } is only a shallow copy. It copies the top-layer pairs, but when a value is a nested object, only its rope is copied: the inner basket stays shared. So b.p and a.p lead to the same basket; b.p.n = 9 changes it for both. To truly separate them you need a deep copy (for example structuredClone).

What the levels ask

  1. Fill in each expression's final value after the code runs.
  2. After b.x = 9, what is a.x?
  3. After b.x = 9 on the spread copy, what is a.x?
  4. After b.push(4), what is a.length?
  5. After b.push(4) on the copy, what are a.length and b.length?
  6. After b[0] = 99, what is a[0]?
  7. After b.p.n = 9 (b is a spread copy of a), what is a.p.n?
  8. b is a spread copy of a. After b.x = 5 and b.p.n = 7, fill in a.x and a.p.n.
  9. After c.v = 7, what is a.v?
  10. After b = { x: 5 }, what is a.x?
  11. After arr[0].n = 5, what is o.n?
  12. b = [...a]. After b[0].n = 9, what is a[0].n?

And more, 18 levels in all.