Spread Syntax in JavaScript (...)

Hero image for Spread Syntax in JavaScript (...). Image by Flash Dantz.
Hero image for 'Spread Syntax in JavaScript (...).' Image by Flash Dantz.

When working with iterables in JavaScript (such as arrays, objects or strings), it can be handy to use the spread operator to cut down on code and keep everything readable. Spread syntax allows you to pass the elements of an iterable (for example the elements within an array), through to a function individually. In simplest terms, it means you can write functionality essentially like foreach loops with a single expression and operator.

The spread operator, ..., can be used in a variety of situations to work with iterables so let's take a look at a few of those now:


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

Spread syntax is now common with both arrays and objects. With arrays it is useful for concatenation, copying and passing values into a function. With objects it is often used to create a new object with a few overridden properties.

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

The JavaScript spread syntax is a nifty little operator to handle iterables, and can really help clean up your code, make it nicer to write, and make it easier to read.

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


Planning a platform change?

I help teams make difficult platform work clearer, from architecture decisions and migrations to launch recovery, performance, and search visibility.