JS: Spread Operator

By Xah Lee. Date: . Last updated: .

New in ES2015.

Syntax:

... iterable

The space after the dots can be omitted.

The spread operator is 3 dots , its operand is any iterable.

〔►see JS: Iterable

What it does is effectively remove the bracket of the array.

// spread operator on array
console.log(
    [1, ... [7,8], 6]
); // [ 1, 7, 8, 6 ]

Here's example with variable:

// example of using the spread operator

var aa = [3,4];
var bb = [2, ...aa, 6]; // insert aa in middle, without nesting

console.log(
    bb
); // [ 2, 3, 4, 6 ]

Here's example with array push:

// example of using the spread operator
// push array into a array, without nesting

var a1 = [1, 2];
var a2 = [3, 4, 5];

a1.push( ...a2 );

console.log(
    a1
); // [ 1, 2, 3, 4, 5 ]

Reference

ECMAScript 2015 §ECMAScript Language: Expressions#sec-array-initializer

Like what you read? Buy JavaScript in Depth