JS: Spread Operator (triple dots)

By Xah Lee. Date: . Last updated: .

Spead iterable (array etc)

(new in ECMAScript 2015)

...iterable

insert the values of a Iterable Object into a array, or as arguments to a function.

  • [1,...[2,3],4] becomes [1,2,3,4].
  • f(1,...[2,3],4) becomes f(1,2,3,4).
/* insert an array's elements into another. */
console.log(
 [2, ...[3, 4], 6],
);
// [ 2, 3, 4, 6 ]
/* feed array to a function as multiple args */
console.log(
 ((x, y) => (x + y))(...[3, 4]),
);
// 7
/* turn string into array of chars */
console.log(
 [..."a🦋c"],
);
// [ "a", "🦋", "c" ]
/* insert map entries into array */
console.log(
 [9, ...(new Map([[3, 23], [4, 72]]))],
);
// [ 9, [ 3, 23 ], [ 4, 72 ] ]

Spread object

(new in ECMAScript 2018)

...object

insert Enumerable properties of object into a Object Literal Expression.

e.g. { ...{ a:1, b:2}, c:3} becomes { a:1, b:2, c:3}.

Later key overrides previous.

/* Merge Objects */
console.log(
 { b: 3, ...{ a: 1, b: 2 }, b: 4 },
);
// { b: 4, a: 1 }

// later key overrides previous