ES6 JavaScript Spread Syntax

The spread syntax is usually used as an argument in function calls to expand an array (e.g. [1,2,3,4]) into a series of arguments 1,2,3,4 to be passed to the function. It can also be used in arrays (see below) and soon, objects. Examples below | MDN docs

JavaScript ES6 Spread Syntax Animation

—ged

ES6 JS Spread Syntax Details

as a function call argument

Use the spread syntax to ‘spread’ an array across function arguments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

// 1) If you have an array like:
const myArray = ['a', 'b', 'c', 'd'];

// 2) Using the 'spread syntax' like so
doWork(...myArray);
// would be the same as
doWork('a', 'b', 'c', 'd').

// NOTE: of course, you can also do this with any builtin or library function
// that takes several arguments. e.g. Date(year, month, date)
const dateInfo = [2019, 3, 3];
const date = new Date(...dateInfo);
// same as: new Date(2019, 3, 3);

with arrays

You can use the spread syntax to compose new arrays from existing arrays.

1
2
const myArray = [1,2,3];
const newArray = [0, ...myArray]; // [0,1,2,3,4]

‘rest’ vs ‘spread’ Rule of Thumb:

If you see ...varName in a function DEFINITION e.g. function fn(a1, a2, ...others){}, it’s a ‘rest’. Elsewhere, it’s a ‘spread’.

FINAL NOTE:

Don’t allow the number of arguments in a function call to be above 65535 or things will start getting weird/error out.
refs:
MDN mentions hardcoded limit of 65536
Webkit discussion
stackoverflow experiment showing varings maxes per browser

Share