G2Labs Grzegorz Grzęda
JS spread operator
May 27, 2023
All these examples can be run on the ReplIt, setting to NodeJS, HTML/CSS/JS or just entering debug mode on your browser. Hit F12
if you use Google Chrome and select the Console
tag. For Mozilla Firefox, press Ctrl
+Shift
+Z or search for the Debugger
option under the Web Developer
menu item.
Why use it?
Because it’s an easy unroll an array (spread
it across). Spread operator ...
can be used in cases:
- to fill up function call arguments,
- to compose a straight array of objects,
- to destructure an array.
Function calls
To call a function we usually do:
Or we can do this:
Even better, we can spread out many things:
Fill arrays
If we would like to compose an array using another array, without a loop, its hard:
Using the spread operator:
Also, if you want to make a copy
on an array (not just copy the reference to an array, but copy it element by element):
Destructure data
If you want to access say the beginning of an array, use the spread:
Not all gold…
Although the ...
operator is great, it’s not perfect. After all, you can use it only on arrays!
Playing with objects can’t work because: