Spread Syntax in JavaScript (...)

Abstract image used to represent Spread Syntax in JavaScript (...)
Image by Flash Dantz.

When working with iterables in JavaScript, such as arrays and strings, spread syntax can help keep the code readable. It expands their values into an array literal or a function call. Object literals have a related spread form, but a plain object is not iterable by default.

The same ... syntax appears in both cases, with different rules for what gets copied. Let's look at a few examples:


Concatenation

The spread operator allows you to combine two or more arrays into a single one very easily, for example:

const arrayOne = [1, 2, 3];
const arrayTwo = [4, 5, 6];
const arrayThree = [...arrayOne, ...arrayTwo];
console.log(arrayThree);
// [object Array] (6)
// [1,2,3,4,5,6]

Easypeasy!


Function Calls

Concatenation is certainly useful, but there are definitely better uses out there for this operator. For instance, getting the biggest number from an array:

const arrayOne = [2, 4, 6, 8];
console.log(Math.max(...arrayOne));
//=> 8

...or running it through a function you've built yourself:

const arrayOne = [1, 2, 3, 4, 5];
const addUp = (a, b, c, d, e) => {
  console.log(a + b + c + d + e);
};

addUp(...arrayOne);
//=> 15

Obviously, this is a fairly rudimentary example, but suffice it to say: there is a tonne of ways to use this operator besides a pretty ugly addition function!


Arrays, Objects, and Shallow Copies

Array and functioncall spread read values from an iterable. Object spread copies an object's own enumerable properties instead, including symbol properties. That is why { ...plainObject } works, but [...plainObject] throws unless the object provides an iterator.

The important caveat is that spread creates a shallow copy. Nested objects and arrays are still shared by reference. That is fine when you know the data shape, but it can create subtle bugs when you expect a deep clone.


Spread is Not Rest Syntax

The same ... characters are also used for rest syntax, but the direction is different. Spread expands values out. Rest gathers values in. Keeping that distinction clear makes function signatures and object updates easier to read.


The Wrap‑up

Spread is useful for combining values or making shallow copies. Match the form to the data: iterable values for arrays and function calls, enumerable properties for object literals.

One thing to bear in mind though is that you'll have some issues using it in IE (of course).


Have a complex web platform issue?

Tell me what is blocked, what has changed, and what needs to be true after the fix. I'll come back with a practical next step.