Spread Operator: It allows an iterable such as an Array or String to expand in places where 0 or more arguments are expected.
The syntax of the spread operator is ... (three dots) and it introduced in ES6.
Lets see some of examples to understand how actually the spread operator works
Example1: Combining two arrays
If you console.log above then it'll print output like this:
It has converted it into the nested array, but this is not really we want. We want asianCountries in allCountries but as a single array. Here comes the spread operator into pictures.
Now the output will be:
So this way we can combine arrays using spread operator
Example2: Using Math object
I want to get lowest number using Math object from an Array. Let see how spread helps us here.
Lets see what if I tries it without spread
If you try this on console then it'll show output as NaN because Math.min() doesn't work with array as an argument. Now lets see this with spread
The syntax of the spread operator is ... (three dots) and it introduced in ES6.
Lets see some of examples to understand how actually the spread operator works
Example1: Combining two arrays
Example: let asianCountries = ['India','China']; let allCountries = ['Australia','France',asianCountries,'Canada','Japan'];
//Output ["Australia", "France", Array(2), "Canada", "Japan"]
let asianCountries = ['India','China']; let allCountries = ['Australia','France',...asianCountries,'Canada','Japan']; console.log(arr);
["Australia", "France", "India", "China", "Canada", "Japan"]
Example2: Using Math object
I want to get lowest number using Math object from an Array. Let see how spread helps us here.
Lets see what if I tries it without spread
let arr = [10,20,30]; Math.min(arr); console.log(arr); //Output : NaN
let arr = [10,20,30]; Math.min(...arr); console.log(arr); Output: 10
No comments:
Post a Comment