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]

If you have ["a", ...array ,"b"], what it does is effectively remove the out-most brackets of array.

Similarly, if you call a function f( "a", ... iterable ,"b"), what it does is feed the values of iterable to the function as arguments.

Array Example

// 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

const aa = [3,4];
const 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

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

a1.push( ...a2 );

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

Function Example

// function, take 2 args, add them
const f = ((x,y) => (x+y));

const myIterable = [3,4];
// array is a iterable

// call the function
console.log (
 f( ...myIterable ) === 7
); // true

String Example

const ss = "ab αβ";

console.log ( [...ss] ); // [ 'a', 'b', ' ', 'α', 'β' ]

Map Example

const m = new Map([ [3, "n3"], [4, "n4"]]);

console.log( [9, ...m]); // [ 9, [ 3, 'n3' ], [ 4, 'n4' ] ]

Reference

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

Iterable Topic

  1. JS: Interface
  2. JS: Iterable
  3. JS: Iterator
  4. JS: for-of Loop
  5. JS: Spread Operator
  6. JS: Generator
  7. JS: Generator Function
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc