JavaScript Spread Operator
Spread Operators allows an iterable such as an array or string where zero or more arguments are expected. It allows us to obtain a list of parameters from an array. The spread operator is represented using ... operator.
Syntax:
var variableX = [...data];
The spread operator can be used in a function call or for an array literals or string or object literals.
Function Call Notation
functionName(...parameters);
Array literals Notation
[...arrayList,3,4,5];
Object literals Notation
let newObject = {...obj1};
Using spread operator in a function call:
In the above program we have a addValues() function with 3 parameters. Now we can call addValues() function by applying spread operator with array of integers. Here the array of values length must match the number of parmaters in the addValues() function.
Using spread operator in object:
Result
{name: "Mark", gender: "male", isManager: true}
In the above code we have created an object employee with name and gender as parameters. Now we create an object manager by combining the properties of employee object and add additional parameter isManager.
Using spread operator in an array:
The spread operator can be used in many cases, like when we want to perform expand, copy, concat operations.
Suppose if we want to concat two array and form a new array by combining the two array values we can achieve it by doing as mentioned below.
Result
[1,2,3,4,5,6,7,8,9,10]
Suppose if we want to copy the values in an array to an other array we can do something like below.
Result:
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
In the above example if we try to copy the values in arr1 to arr2 by assigning arr2 to arr1. Now when we push any value to arr1 will also affect arr2 since array is reference typed. If we want seperate copy in arr2 variable then you need to do something like below.
Result:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5]
Suppose if we want to expand an array you can do something like below.
Result:
[1,2,3,4,5,6,7,8,9,10]
Suppose if we want to perform any Math operation like finding min and max operation we can use spread operator.
Example
Math.max(1,2,3,4,5) will return 5 which is the maximum number in the list. Suppose if we have an array in which we need to find the maximum value and if we apply one like below
Math.max([1,2,3,4,5]) will return 'NaN'. We can fix this by something like below.
Result
5