Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 156 ยท Objects

Spread and Rest

Learn the two jobs of JavaScript's three dots. Spread arrays and objects to copy and merge them, and use rest to collect leftover arguments and properties.

JavaScript uses three dots, ..., for two opposite jobs. Spread takes a collection and expands it into individual pieces: items into an array, properties into an object, or arguments into a function call. Rest does the reverse: it gathers several pieces into one array or object.

The syntax is identical, so the trick is to look at where the dots appear. When they sit where values are being produced (an array literal, an object literal, a function call), they spread. When they sit where values are being received (a destructuring pattern or a parameter list), they collect the rest. This lesson covers both, with the everyday patterns you'll use constantly: copying, merging, adding items without mutation and writing functions that accept any number of arguments.

Spreading arrays

Inside an array literal, ...array drops all of that array's items in place:

JS Spread into array literals

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Spread builds a new array every time, so the originals stay as they were. That makes it a favorite in code that avoids mutation, such as state updates in UI frameworks. Compare list.push(item), which changes list, with [...list, item], which leaves list alone and returns a fresh array.

Spreading works on any iterable, not only arrays. That is why [..."hey"] splits a string into characters and [...new Set(values)] is the classic one-liner for removing duplicates (more in Sets).

Spreading into function calls

In a call, ...array passes each item as a separate argument. Functions such as Math.max() expect separate numbers, not an array, so spread is the bridge:

JavaScript
const scores = [71, 94, 88, 62];

console.log(Math.max(scores));    // NaN, an array is not a number
console.log(Math.max(...scores)); // 94, same as Math.max(71, 94, 88, 62)

const parts = [2026, 0, 15]; // year, month index, day
const date = new Date(...parts);

You can mix spread with ordinary arguments in any order, for example Math.min(0, ...scores, 100). Older code did the same job with Math.max.apply(null, scores); you'll learn about apply in call, apply and bind, but spread is the modern way.

Very large arrays. Every spread item becomes a real argument, and engines limit how many arguments a call can take (usually tens of thousands or more). For huge arrays, use a loop or reduce instead of Math.max(...hugeArray).

Spreading objects

Inside an object literal, ...obj copies that object's own enumerable properties into the new object. This is the standard way to copy and merge plain objects:

JS Copying and merging objects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The rule to remember: properties are written left to right, and when two have the same key, the later one wins. So put defaults first and overrides last. That single rule explains the "override one property" pattern, { ...obj, key: newValue }, which you'll see everywhere.

The last example uses a small trick. Spreading false, null or undefined into an object adds nothing, so ...(condition && { key: value }) adds the property only when the condition is truthy.

Object spread does the same job as Object.assign({}, a, b) from Working with Objects, but it reads more clearly and always creates a new object.

Spread copies are shallow

Spread copies one level deep. If a property holds an object or array, the copy gets a reference to the same nested value:

JS Shallow copy surprise

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Changing a top-level property of the copy is safe. Changing inside a nested array or object affects both, because there is only one nested array. The fix is to spread each level you plan to change, as safeCopy does. For a full deep copy, use structuredClone(), covered in Copying Objects: Shallow and Deep.

A few other details of object spread:

  • Only own, enumerable properties are copied. Inherited methods from the prototype are not.
  • Getters are run, and their current value is copied as a plain property. The copy doesn't keep the getter. You'll meet getters in the next lesson.
  • Spreading a string into an object gives index keys: { ..."hi" } is { 0: "h", 1: "i" }. You rarely want this.

Rest parameters

Now the other direction. In a function's parameter list, ...name collects all remaining arguments into a real array:

JS Rest parameters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A rest parameter must be last, and there can be only one. function f(...a, b) is a syntax error, because nothing could ever reach b.

Rest parameters replace the old arguments object, which you'll see in older code. arguments is array-like but not a real array (no map or reduce), it holds all arguments instead of just the leftover ones, and it doesn't exist in arrow functions. Prefer rest parameters in new code. The Parameters and Arguments lesson compares them side by side.

Rest in destructuring

You saw this briefly in Destructuring. At the end of a pattern, ...name collects everything that wasn't picked out:

JavaScript
const [winner, runnerUp, ...others] = ["Ivy", "Max", "Sol", "Ren", "Ola"];
console.log(winner);  // "Ivy"
console.log(others);  // ["Sol", "Ren", "Ola"]

const product = { id: 7, name: "Lamp", price: 39, internalCode: "X-77" };
const { internalCode, ...publicProduct } = product;
console.log(publicProduct); // { id: 7, name: "Lamp", price: 39 }

The object version is the cleanest way to omit properties without mutating the original. Instead of delete product.internalCode, which changes product, you unpack the unwanted keys and keep the rest in a new object. The same rule applies as with parameters: the rest element must come last.

Spread or rest? A quick test

When you see ..., ask what the surrounding code is doing:

Where the dots appear Job Result
Array literal [...a] Spread Items expanded into a new array
Object literal {...o} Spread Properties copied into a new object
Function call f(...a) Spread Items passed as separate arguments
Parameter list function f(...a) Rest Extra arguments gathered into an array
Array pattern const [x, ...a] = โ€ฆ Rest Remaining items gathered into an array
Object pattern const {x, ...o} = โ€ฆ Rest Remaining properties gathered into an object

Left side of = or in a parameter list: rest. Anywhere else: spread.

Putting it together

Here's a small, realistic example: updating an item in a list without mutating anything. It uses object spread to change one item and array spread to build the new list.

JS Immutable update

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Unchanged items are shared between the old and new arrays, which is efficient and perfectly safe as long as you never mutate them. You'll learn more about map in map, filter, reduce and forEach.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is merged.color after const merged = { color: "red", ...{ color: "blue" } };?

    Properties are written left to right and later keys win, so the spread value "blue" overwrites "red".
  2. 2. In which position are the three dots acting as rest?

    A parameter list receives values, so ...items gathers the arguments into an array. The others all expand values.
  3. 3. const copy = { ...original }; and then copy.tags.push("new"). What happens to original.tags?

    Spread is shallow. Both objects point to the same tags array.
  4. 4. Why is function f(...rest, last) {} invalid?

    Rest gathers every remaining argument, so nothing could ever reach a parameter after it. JavaScript requires it to be last.
  5. 5. How do you get a copy of user without its password property, leaving user unchanged?

    The rest pattern collects every property except password into a new object. delete would mutate user.

Summary

  • ... spreads in array literals, object literals and function calls, and collects (rest) in parameter lists and destructuring patterns.
  • [...a, ...b] and { ...a, ...b } copy and merge without touching the originals; later object keys win.
  • f(...array) passes items as separate arguments, as in Math.max(...scores).
  • Spread copies are shallow: nested objects and arrays are shared.
  • Rest parameters give you a real array of extra arguments and replace the old arguments object.
  • const { unwanted, ...rest } = obj is the clean way to omit properties.

Next: Getters and Setters โ€” properties that run code when you read or write them.