Tuesday 23 April 2019

JavaScript ES6 Spread Operator (...)

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

Example:

let asianCountries = ['India','China'];
let allCountries = ['Australia','France',asianCountries,'Canada','Japan'];
If you console.log above then it'll print output like this:

//Output

["Australia", "France", Array(2), "Canada", "Japan"]
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.

let asianCountries = ['India','China'];
let allCountries = ['Australia','France',...asianCountries,'Canada','Japan'];

console.log(arr);
Now the output will be:

["Australia", "France", "India", "China", "Canada", "Japan"]
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

let arr = [10,20,30];
Math.min(arr);
console.log(arr);

//Output : NaN
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

let arr = [10,20,30];
Math.min(...arr);

console.log(arr);

Output: 10

No comments:

Post a Comment