Using the JavaScript spread operator

Published December 7, 2020

In JavaScript, the spread syntax is an ellipsis of three dots ... used to expand an iterable object into a list of its arguments. The spread syntax spreads array and objects into separate arguments.

The spread operator is quick and easy to use for adding items to arrays, combining arrays or objects, and spreading an array or object out. The spread operator was added to JavaScript in ES6 (ES2015), just like the rest parameters, which have the same syntax - an ellipsis of three dots.

Spreading an array

Let's look at an example use case of the spread operator using the Math.max() function. This function expects separate numbers. Trying to pass an array to it will give us a NaN (not a number) error.

Math.max(1, 3, 5); // 5
Math.max([1, 3, 5]); // NaN

Let's fix this NaN error by using the spread operator.

Math.max(...[1, 3, 5]); // 5

The spread operator placed before the array has spread out our [1, 3, 5] array into separate values of 1, 3, and 5.

Copying an array

The spread operator makes it easy to copy an array.

const brands = ['honda', 'audi', 'toyota', 'mazda'];
const brandsCopy = [...brands];

brands[0] = 'nissan'; // only element 0 of the brands array is changed
console.log(brands); // ['nissan', 'audi', 'toyota', 'mazda'] 
console.log(brandsCopy); // ['honda', 'audi', 'toyota', 'mazda'] 

Combining an array

The spread operator makes it easy to combine or concatenate arrays.

const brands = ['honda', 'toyota', 'nissan'];
const luxuryBrands = ['acura', 'lexus', 'infinity'];

console.log([...brands, ...luxuryBrands]); // ["honda", "toyota", "nissan", "acura", "lexus", "infinity"]

Adding items to an array

The spread operator makes it easy to add items to an array.

const techBrands = ['apple', 'microsoft', 'google'];
const allBrands = ['sony', 'samsung', ...techBrands];

console.log(allBrands) // ["sony", "samsung", "apple", "microsoft", "google"]

Combining objects

The spread operator makes it easy to combine objects.

const product = { name: 'apple', color: 'red' };
const cost = { price: 1.99, sale: 0.99 };
const item = { ...product, ...cost, quantity: 10 };

console.log(item); // {name: "apple", color: "red", price: 1.99, sale: 0.99, quantity: 10}