A spread operator (...) provides a quick way to expand a Javascript object or array.
Array or object is a collection of values. Accessing individual values within the array will require one to use a loop.
1
2
3
4
5
6
7
8
9
10
constfruits=["orange","apple"];for(leti=0;i<fruits.length;i++){console.log("fruit: ",fruits[i]);}/* output
fruit: orange
fruit: apple
*/
With the advent of the spread operator, the above operations become easier and more readable. Array can now be ‘destructured’ with a single statement.
1
2
constfruits=["orange","apple"];console.log("fruits: ",...fruits);//fruits: orange apple
Accessing variables in an object is simpler, but would still need multiple statements.
1
2
3
4
5
6
7
8
constapple={color:"red",size:"small"};console.log("apple color: ",apple["color"]);console.log("apple size: ",apple["size"]);/* output
apple color: red
apple size: small
*/
Instead, we can do this -
1
2
const{color,size}={...apple};console.log(color+", "+size);// red, small
Individual variables and values can go their own way after being initialized.
Wait, there’s more
Since spread operator can provide access to the elements, it now finds ‘wide spread’ use for multiple things that needed elaborate coding by hand earlier.
This looks simple but is super useful in functions where there may be a tonne of variables being passed and we are interested only in one or two. For example, multiple variables are passed to ‘controller’ functions in an API, but we just want to extract data using a specific variable.