JS: Spread Operator

By Xah Lee. Date: . Last updated: .

New in JS2015.

Spread Operator

...iterable
“spread” the values of a Iterable Object into a array or arguments of a function.
For example,
[1,...[2,3],4] becomes [1,2,3,4].
f(1,...[2,3],4) becomes f(1,2,3,4).
...object
New in JS2018. “spread” Enumerable properties of object into a Object Literal Expression.
For example,
{ ...{ a:1, b:2}, c:3} becomes { a:1, b:2, c:3}. Order matters, because object property preserves order (JS2020).

Example: Embed Array Elements into Array

// example of using the spread operator

const aa = [3, 4];

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

console.log([2, 3, 4, 6].every((x, i) => (bb[i] === x)));

Example: Feed Array to Function as Multiple Args

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

Example: Turn String into Array of Chars

const ss = "ab αβ";

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

Example: Merge Objects

const x1 = { a: 1, b: 2 };
const x2 = { ...x1, c: 3 };
console.log(x2); // { a: 1, b: 2, c: 3 }

Example: Merge Maps

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

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

JavaScript, Iterable 🌟

BUY ΣJS JavaScript in Depth