ES6: Spread Operator

6min read

The spread syntax allows arrays, objects and array like objects (e.g. arguments object, DOM node objects) to be expanded in places where multiple arguments (for function calls) are expected. In order to use the spread operator simply write three dots “…” preceeding the expression that should get “spread”.

The Spread Operator is a sibling of the Rest Parameter which both share the same syntax. It is a great new feature and probably best observed in action.

The better apply

We can use the spread operator instead of apply to call a function and pass it an array of arguments.

ES5

ES6

Merging arrays

We can use the spread operator to merge multiple arrays.

ES5

ES6

The array can be spreaded anywhere it is necessary.

As initially stated it works not only for arrays and array-like objects but also objects itself. We can use the spread operator to create a fresh new copy of an object that inherits all the properties of the cloned object. But be aware: the spread operator is not suitable to deep clone an object as it goes only one level deep.

Copy an array

We can use it to make a frew new copy of an array without a reference.

ES5

ES6

Convert array-like objects to arrays

Sometimes it is necessary to convert an array-like object to an array, e.g. in order to use methods which are only available for arrays such as filter, map or reduce.

ES5

ES6