A spread operator is represented by the ... token. A spread operator splits an iterable object into its individual values.
A spread operator can be placed wherever multiple function arguments or multiple elements (for array literals) are expected in code.
The spread operator is commonly used to spread the values of an iterable object into the arguments of a function. Let's take the example of an array and see how to split it into the arguments of a function.
To provide the values of an array as a function argument, you can use the apply() method of Function. This method is available to every function. The following example demonstrates:
function myFunction(a, b) {
return a + b;
}
var data = [1, 4];
var result = myFunction.apply(null, data);
console.log(result); //Output "5"
Here, the apply method takes an array, extracts the values, passes them as individual arguments to the function, and then calls it.
Here's an example using the modern way, that is, with the spread operator:
function myFunction(a, b) {
return a + b;
}
let data = [1, 4];
let result = myFunction(...data);
console.log(result); //Output "5"
During runtime, before the JavaScript interpreter calls the myFunction function, it replaces ...data with the 1,4 expression:
let result = myFunction(...data);
The previous code is replaced with:
let result = myFunction(1,4);
After this, the function is called.