DevPath · Learn to code ESPTEN

Modern JavaScript (ES6+)

Spread and rest (...)

The three-dot operator: ...

The same ... symbol does two opposite things depending on the context: spread (expand) and rest (group).

Spread: expand

It spreads out the elements of an array or object somewhere else.

const a = [1, 2];
const b = [3, 4];
const together = [...a, ...b]; // [1, 2, 3, 4]

const copy = [...a];           // shallow copy of a

It also works with objects to copy and combine:

const base = { x: 1, y: 2 };
const extended = { ...base, z: 3 }; // { x: 1, y: 2, z: 3 }

If there are duplicate keys, the last one wins: { ...base, x: 9 } leaves x: 9.

Rest: group

In parameters or in destructuring, ... groups the remaining elements into an array.

function sumAll(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}
sumAll(1, 2, 3, 4); // 10
const [first, ...rest] = [10, 20, 30, 40];
console.log(first); // 10
console.log(rest);  // [20, 30, 40]

Examples

Combine arrays and objects with spread

const fruits = ["pear", "grape"];
const moreFruits = ["apple", ...fruits, "kiwi"];
console.log(moreFruits); // ["apple", "pear", "grape", "kiwi"]

const user = { name: "Ana", role: "user" };
const admin = { ...user, role: "admin" };
console.log(admin); // { name: "Ana", role: "admin" }
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← DestructuringOptional chaining and nullish coalescing →