Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 26 of 58

Rest and spread

Use the three-dot syntax in JavaScript: rest parameters collect arguments into an array, and spread expands arrays and objects, including copying and merging.

10 minFunctionsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite functions that accept any number of arguments, call functions with an array of values, and copy or merge arrays and objects without changing the originals.

After this lesson you can read and write the ... syntax. It appears in modern JavaScript all the time, and it solves two common jobs: handling any number of arguments, and copying or combining arrays and objects.

One symbol, two jobs

Three dots, ..., do opposite things depending on where you write them.

  • Rest gathers several values into an array. It appears in a function's parameter list (and in destructuring).
  • Spread spreads a collection out into separate values. It appears in function calls and in array or object literals.

A handy way to remember: if the dots are in the place where something is being defined, they collect. If they are where values are being used, they expand.

Rest parameters

Say you want a function that adds any number of values. You do not know in advance how many:

javascript
function sum(...numbers) {
  let total = 0;
  for (const number of numbers) {
    total += number;
  }
  return total;
}

console.log(sum(1, 2));        // 3
console.log(sum(1, 2, 3, 4));  // 10
console.log(sum());            // 0

numbers is a real array, so every array method works on it. Without arguments it is an empty array, not undefined.

A rest parameter can follow normal parameters. It must be the last one:

javascript
function introduce(greeting, ...names) {
  return greeting + " " + names.join(" and ");
}

console.log(introduce("Hello", "Asha", "Ben", "Chen")); // Hello Asha and Ben and Chen

Only one rest parameter is allowed per function.

Older code uses a special variable named arguments, which looks like an array but is not one, and does not exist in arrow functions. Prefer rest parameters in new code.

Spread in function calls

Some functions take separate arguments, but your data is in an array. Math.max is an example. Spread bridges the gap:

javascript
const scores = [72, 95, 88];

console.log(Math.max(scores));     // NaN
console.log(Math.max(...scores));  // 95

...scores turns the array into three arguments, exactly as if you had typed Math.max(72, 95, 88).

Spread in arrays

Inside an array literal, spread copies the items of another array into the new one. You can mix in extra items anywhere:

javascript
const fruits = ["apple", "banana"];
const more = ["kiwi", "mango"];

const all = [...fruits, "cherry", ...more];
console.log(all); // [ 'apple', 'banana', 'cherry', 'kiwi', 'mango' ]

const copy = [...fruits];
copy.push("grape");
console.log(fruits); // [ 'apple', 'banana' ]  (original unchanged)
console.log(copy);   // [ 'apple', 'banana', 'grape' ]

This is the usual way to copy an array or to add an item without changing the original, which is a habit that avoids many bugs. Spread also works on strings and other iterable values: [..."hey"] is ["h", "e", "y"].

Spread in objects

The same idea works for objects, copying properties into a new one:

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  function show(text) {
    out.textContent += text + "\n";
  }

  const defaults = { theme: "light", fontSize: 16, sidebar: true };
  const userChoices = { theme: "dark", fontSize: 18 };

  // Later properties win
  const settings = { ...defaults, ...userChoices };
  show(JSON.stringify(settings));

  // Update one property in a copy
  const updated = { ...settings, sidebar: false };
  show(JSON.stringify(updated));
  show(JSON.stringify(settings));
</script>

When two sources have the same property, the one written later wins. That makes "defaults first, overrides after" an easy pattern. The original settings is not touched, which is exactly what libraries such as React expect when you update state.

Spread makes a shallow copy

Spread copies only the top level. If a property holds an object or array, the new object holds a reference to the same one:

javascript
const original = { name: "Asha", address: { city: "Delhi" } };
const copy = { ...original };

copy.name = "Ben";
copy.address.city = "Pune";

console.log(original.name);         // Asha
console.log(original.address.city); // Pune

The name stayed separate, but address is shared, so the change leaked into the original. For a full independent copy, copy the nested part too (address: { ...original.address }) or use the built-in structuredClone(original), which makes a deep copy of plain data.

Rest and spread together

You can combine the two ideas. A function can collect the rest of its arguments, then pass them on:

javascript
function logWithLabel(label, ...values) {
  console.log(label, ...values);
}

logWithLabel("Scores:", 10, 20, 30); // Scores: 10 20 30

The same dots are also used in destructuring, where const [first, ...others] = list puts the remaining items into a new array. See Destructuring later in the course. Earlier you met parameters in Parameters, defaults and return values; rest is another tool for that part of a function.

Copying versus referencing

Assigning an array to a new variable does not copy it. Both names point at the same array, so a change through one shows up through the other. Spread gives you a genuine new array:

javascript
const a = [1, 2, 3];
const same = a;
const copy = [...a];

same.push(4);
console.log(a);    // [ 1, 2, 3, 4 ]
console.log(copy); // [ 1, 2, 3 ]

Reaching for spread whenever you need "the same list, plus a change" keeps your original data safe.

Common mistakes

Putting rest anywhere but last. function f(...a, b) is a syntax error.

Passing an array where separate arguments are expected. Math.max(scores) gives NaN. Add the spread.

Spreading an object into an array. [...{ a: 1 }] throws a TypeError, since plain objects are not iterable. Spread an object only inside { }.

Thinking spread is a deep copy. Nested data is shared. Change a nested value in the copy and the original changes too.

Getting the order wrong when merging. The last source wins, so { ...overrides, ...defaults } would let the defaults win.

Exercise

Write average(...numbers) that returns the average of any number of values, and returns 0 when none are given. Then write a function addItem(list, item) that returns a new array with the item added at the end, without changing list, using spread. Finally, merge { a: 1, b: 2 } and { b: 3, c: 4 } into one object and show the result. Predict the value of b first.

Next: Recursion.

Key points

  • The three dots mean rest when they collect values into an array and spread when they expand values out.
  • A rest parameter must be last in the parameter list and holds all remaining arguments as a real array.
  • Spread in a call passes the items of an array as separate arguments.
  • Spread in an array or object literal copies or merges items into a new array or object.
  • Spread makes a shallow copy, so nested objects and arrays are still shared with the original.

Check yourself

1. In function sum(...numbers) { }, what is numbers when you call sum(1, 2, 3)?
2. Where must a rest parameter be placed?
3. What does Math.max(...[3, 9, 4]) return?
4. const copy = { ...original }; copy.address.city = 'Pune'; What happens to original.address.city?