JavaScript lesson · 18 min

JavaScript Spread and Rest

Copy arrays and objects with spread, and collect extra function arguments with rest parameters.

Code runs locally in your browser

What you will practice

  • Copy arrays with spread.
  • Copy and override object properties.
  • Collect extra function arguments with rest.

What this means

The three dots `...` have two common meanings. In one place they spread values out. In another place they gather values together.

Spread is often used to copy arrays or objects without changing the original value.

Rest parameters collect many function arguments into one array so the function can handle a flexible number of inputs.

If this is your first time seeing this

Spread copies or expands values. Rest gathers leftover values into one array.

The same three dots look identical, so always ask: are values being spread out or collected in?

Mini glossary

Spread
Using `...` to expand array items or object properties into a new place.
Rest parameter
Using `...` in a function parameter to collect remaining arguments.
Mutation
Changing an existing value instead of creating a new one.

Example from everyday life

Spread is like laying all cards from one pile onto the table. Rest is like gathering all leftover cards into one new pile.

How it works step by step

  1. `const allTools = [...baseTools, "URL Parser"]` copies the old array and adds one item.
  2. `const updatedProfile = { ...profile, role: "admin" }` copies the old object and overrides one property.
  3. `function summarize(first, ...others)` keeps the first argument separate and collects the rest into an array.
  4. The original `profile` object still has its old role because spread made a new object.

Where you will use this

  • A UI updates one setting while keeping the rest of the settings object.
  • A list adds a new item without mutating the old list.
  • A logging function accepts any number of labels or tags.

Before you run the code

Spread/rest is common in modern JavaScript because it helps write code that avoids accidental mutation.

The same `...` syntax can feel confusing at first. Ask whether the code is spreading values out or collecting values in.

Common beginner mistakes

  • Thinking spread makes a deep copy of everything. Nested objects can still be shared.
  • Forgetting that object properties written later override earlier ones.
  • Mixing up rest parameters with the old `arguments` object.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingCreates a copied array with a new item
WaitingCollects remaining arguments with rest

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Add another item to `baseTools` and run the code.
  • Change `role: "admin"` to `role: "viewer"`.
  • Add more arguments to `summarize` and watch the count change.