JavaScript: Spread Operator
New in JS2015.
...iterable
-
“spread” the values of a Iterable 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 console.log( [1, ... [7,8], 6] ); // [ 1, 7, 8, 6 ]
Example with variable:
// example of using the spread operator const aa = [3,4]; const bb = [2, ...aa, 6]; // insert aa in middle, without nesting console.log( bb ); // [ 2, 3, 4, 6 ]
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' ] ]