JavaScript: Spread Operator
New in JS2015.
...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)
becomesf(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).
Array Example
// spread operator on array const aa = [1, ...[7, 8], 6]; console.log([1, 7, 8, 6].every((x, i) => (aa[i] === x)));
Example with variable:
// 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 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', ' ', 'α', 'β' ]
Object Example
const x1 = { a: 1, b: 2 }; const x2 = { ...x1, c: 3 }; console.log(x2); // { a: 1, b: 2, c: 3 }
Map Example
const m = new Map([[3, "n3"], [4, "n4"]]); console.log([9, ...m]); // [ 9, [ 3, 'n3' ], [ 4, 'n4' ] ]