JavaScript Arrays Array spread / rest

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Spread operator

6

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 operator also acts upon strings, separating each individual character into a new string element. Therefore, using an array function for converting these into integers, the array created above is equivalent to the one below:

let arr = [1, 2, 3, ...[..."456"].map(x=>parseInt(x))]; // [1, 2, 3, 4, 5, 6]

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

let arr = [..."123456"].map(x=>parseInt(x)); // [1, 2, 3, 4, 5, 6]

If the mapping is not performed then:

let 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) { }
let args = [0, 1, 2];

myFunction(...args);

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

Rest operator

The rest operator does the opposite of the spread operator by coalescing several elements into a single one

[a, b, ...rest] = [1, 2, 3, 4, 5, 6]; // rest is assigned [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]


Got any JavaScript Question?