JS: Spread Operator (triple dots)
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)becomesf(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
Triple dots in assignment pattern
here, the triple dots is not operator, but just syntax for pattern.
/* Capture rest elements as a array */ let [a, b, ...c] = [1, 2, 3, 4, 5]; console.log(a, b, c); // 1 2 [3,4,5] // assignment pattern for object rest properties let { dog, ...restP } = { bird: 1, cat: 2, dog: 3 }; console.log(dog); // 3 console.log(restP); // { bird: 1, cat: 2 }