Course outline · 0% complete

0/27 lessons0%

Course overview →

Spread, rest, ?. and ??

lesson 8-2 · ~11 min · 21/27

Three dots, two meanings

... is spread when it expands a collection into pieces, and rest when it collects pieces into an array.

  • Spread into a new array or object: [...list, 4], { ...defaults, port: 3000 }. Later object keys overwrite earlier ones, which makes spread the standard way to copy-with-changes.
  • Rest in parameters: function sum(...nums) packs every argument into a real array.

Spread copies are shallow: nested objects are still shared. Hold that thought for the capstone (lesson 10-3).

These few characters are the daily texture of modern JavaScript: copying state without mutating it (spread), variadic helpers (rest), and surviving missing data (?. and ??). They also headline the "modern JS" round of interviews.

Code exercise · javascript

Run it. Spread builds a changed copy without touching the original, and rest lets sum accept any number of arguments.

Quiz

`const copy = { ...state };` where `state.user` is a nested object. Is `copy.user` independent of `state.user`?

Safe access: ?. and ??

  • Optional chaining user.profile?.email returns undefined instead of crashing when profile is null or undefined. Works for calls too: callback?.().
  • Nullish coalescing value ?? fallback uses the fallback only for null/undefined.

The interview trap is ?? versus ||: the old || falls back on ANY falsy value, so a legitimate 0 or "" gets replaced. ?? respects them, matching how destructuring defaults treated undefined in lesson 8-1.

Code exercise · javascript

Run it. The user set volume to 0 on purpose. `||` stomps on it, `??` keeps it, and `?.` survives the missing profile.

Quiz

A user typed an empty search string: `""`. Which expression preserves it instead of replacing it with the default?

Code exercise · javascript

Your turn. Implement `merge(base, overrides)` returning a NEW object with overrides winning, and `first(...items)` returning its first argument or `"none"` when called with nothing (use `??`).