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
|
const fruits = ["orange", "apple"];
for (let i = 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
|
const fruits = ["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
|
const apple = { 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.
Clone object or array
1
2
3
4
5
6
7
|
const apple = { color: "red", size: "small" };
const orange = { ...apple };
console.log("orange: ", orange); // orange: { color: 'red', size: 'small' }
orange["color"] = "orange";
console.log("orange: ", orange); // orange: { color: 'orange', size: 'small' }
console.log("apple: ", apple); // apple: { color: 'red', size: 'small' }
|
Merge two arrays or objects
1
2
3
4
5
|
const fruits = ["orange", "apple"];
const addFruit = ["grapes"];
const allFruits = [...fruits, ...addFruit];
console.log("all fruits: ", allFruits); // all fruits: [ 'orange', 'apple', 'grapes' ]
|
Split variables
This is especially useful in a function.
1
2
3
4
5
6
7
|
function sum(x, y) {
console.log("x", x); // 4
console.log("y", y); // 5
return x + y;
}
const arr = [4, 5];
console.log("sum: ", sum(...arr)); // 9
|
In case of an object, this can also be partial -
1
2
3
4
5
|
function sum({ oneInt, twoInt, others }) {
return oneInt + twoInt;
}
const obj = { oneInt: 1, twoInt: 2, threeInt: 3, fourInt: 4 };
console.log("partial sum", sum(obj)); // 3
|
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.