35 min·intermediate

Lesson 6

Spread, rest & immutability

Build a practical mental model for spread, rest & immutability and use it in working JavaScript.

By the end, you will be able to…

  • Explain spread, rest & immutability in your own words
  • Use spread, rest & immutability in a small program
  • Recognize and debug a common failure mode

Build the mental model

Spread (...) copies enumerable properties out of an object or array; rest (...) collects remaining arguments into a single array parameter. Together they support an immutable style: build a new value instead of mutating the old one.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: { theme: "light" } 6

Why this matters

Immutable updates make change tracking predictable — you can compare old vs. new by reference instead of deep-inspecting for mutations.

Real-world example

Every React setState({ ...state, field: value }) call and Redux reducer relies on this exact spread pattern.

Common mistakes

  • Assuming spread deep-copies nested objects (it only copies one level)
  • Forgetting that property order matters — later spread properties overwrite earlier ones
  • Mixing up rest parameters (...args in a function signature) with spread (...arr in a call)

Try it yourself

Challenge

Write addItem(cart, item) that returns a new array with item appended, without mutating cart.

Practice

Knowledge check

How deep does object spread ({ ...obj }) copy?

Summary

Use spread to build new objects/arrays immutably, and rest to collect variable arguments.