JS: Spread Operator (triple dots)

By Xah Lee. Date: . Last updated: .

(new in JS: 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. */
const xx = [3, 4];
const yy = [2, ...xx, 6];
console.log(yy);
// [ 2, 3, 4, 6 ]
/* feed array to function as multiple args */
const ff = (x, y) => (x + y);
console.log(ff(...[3, 4]));
// 7
/* turn string into array of chars */
const xx = "ab αβ";
console.log([...xx]);
// [ "a", "b", " ", "α", "β" ]
/* insert map entries into array */
const xm = new Map([[3, "n3"], [4, "n4"]]);
console.log([9, ...xm]);
// [ 9, [ 3, "n3" ], [ 4, "n4" ] ]
...object

(new in JS: ECMAScript 2018)

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 */
const xx = { a: 1, b: 2 };
console.log({ b: 3, ...xx, b: 4 });
// { b: 4, a: 1 }

// later key overrides previous

JavaScript. Iterable, Iterator