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!


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).


Categories:

  1. ES6
  2. Front‑End Development
  3. JavaScript