Array spread rest

suggest change

Spread operator

With ES6, you can use spreads to separate individual elements into a comma-separated syntax:

let arr = [1, 2, 3, ...[4, 5, 6]];  // [1, 2, 3, 4, 5, 6]

// in ES < 6, the operations above are equivalent to
arr = [1, 2, 3];
arr.push(4, 5, 6);

The spread syntax also works on strings, separating each character into its own element. Mapping those characters with an arrow function produces numbers, so the array above is equivalent to:

const arr = [1, 2, 3, ...[..."456"].map(Number)]; // [1, 2, 3, 4, 5, 6]

Or, using a single string, this could be simplified to:

const arr = [..."123456"].map(Number); // [1, 2, 3, 4, 5, 6]

If the mapping is not performed then:

const arr = [..."123456"]; // ["1", "2", "3", "4", "5", "6"]

The spread operator can also be used to spread arguments into a function:

function myFunction(a, b, c) { }
const args = [0, 1, 2];

myFunction(...args);

// in ES < 6, this would be equivalent to:
myFunction.apply(null, args);

Rest operator

Rest syntax does the opposite of spread by collecting several elements into one array:

const [a, b, ...rest] = [1, 2, 3, 4, 5, 6]; // rest is [3, 4, 5, 6]

Collect arguments of a function:

function myFunction(a, b, ...rest) { console.log(rest); }

myFunction(0, 1, 2, 3, 4, 5, 6); // rest is [2, 3, 4, 5, 6]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents