REST parameters and spread operator in ES-6



Code for this and several other ES-6 features can be found in my github


In ES-5 if a function has to take an arbitrary number or parameters, the exact count of which is decided only during run time, the only option was to construct an array and pass it as a parameter.
In ES-6 a simpler and more expressive notation has been introduced called the RESTparameters, which are represented using the spread operator.
Syntax for the spread operator is to prefix the variable name with three periods.
For example, REST parameter “a” is represented using the spread operator as follows:
...a
These parameters are ultimately converted into an array by the spread operator, there by taking the array creation responsibility away from the developer.
Let us consider a few use cases for these new operators.
CASE 1: Passing arbitrary number of parameters.
ES-5:

var add = function(a,b){     
    console.log(a+(b.reduce((x,y)=>{return x+y}))); 
}; 
add(1,[2,3,4]);
As shown above an array has to be manually constructed and passed to variable “b”.
The same thing can be expressed in ES-6 as follows:

var add = function(a,...b){     
    console.log(b.reduce((x,y)=>{return x+y}),a); 
}; 
add(1,2,3,4); //gives 10
add(1,2,3,4,5); //gives 15
As it is expressed above, the same function can be invoked with different number of parameters, and the trailing parameters will be clubbed together as an Array and sent to the last variable.
CASE 2:
We have just seen how REST parameters can be used to club individual variables into an array. 
If an array is prefixed with spread operator, it can disintegrate the array into individual elements.
This can be used to represent an Array within another array as follows:

var b = [4,5,6,7]
var a= [1,2,3,...b,9]
console.log(a) //[1, 2, 3, 4, 5, 6, 7, 9]
This can be useful in scenarios where we need an array which is fetched from a RESTservice to be embedded into another array.
//CASE 3:
It can be used for concatenating two arrays.
In ES-5:

var a = [1,2,3,4]
var b = [5,6,7,8] 
a.push(b)//[1,2,3,4,[5,6,7,8]]
a.concat(b);
Array.prototype.push.apply(a,b);
In ES-6:

a.push(...b)

Comments

Popular posts from this blog

Docker Commands

Dockerfile

ES-6 classes