Rest Operator in ES6

Both the rest and spread look the same but they are totally different from each other.

The spread operator actually takes an array and then really transforms  it into single values.  While the rest parameters receive a set of single values and convert it into the array whenever we call  a function with multiple parameters. 

<script>

//In ES5 whenever the list of parameters are not fixed. We generally use arguments keyword

//Arguments keyword is very similar to the this variable. This is a variable which each execution context is access to. 

function totalMarks(){

   console.log(arguments);

}

//We have the access to arguments in all the function

totalMarks(99,92,88);

//Output : Arguments(3) [1, 2, 25, callee: ƒ, Symbol(Symbol.iterator): ƒ]

//__proto__ : It tells that what we console is an object. Not an array

//It is not an array. but we want to use it as an array. So that we can iterate through it.

 

function totalMarks(){

   console.log(arguments);

   var argArray = Array.prototype.slice.call(arguments);

   console.log(argArray);

   //Now, we call call forEach on this array

   argArray.forEach(function(mark){

       console.log(mark)

   })

}

totalMarks(11,122,43,567);

//So, the above function will work will all number of arguments

totalMarks(11,122,43,567,43,88);//This also works

 

//Now, let us solve this above problem with ES6

function totalMarks(...marks){

//whatever the parameters we will pass to the totalMarks() , it will transform it into an array and store the items into marks variable.

console.log("the new mark list in ES6",marks);

marks.forEach(function(mark){

       console.log(mark)

   })

}

//here in ES6 , we do not need to convert the parameter to array.Simply the rest parameter is array

totalMarks(11,122,43,567);

//In ES5 parameters is of object type. But, in Es6 rest parameter is of array type

//Apply limit in rest parameter

function totalMarks(passingMark,...marks){

//whatever the parameters we will pass to the totalMarks() , it will transform it into an array and store the items into marks variable.

console.log("the new mark list length with limit in ES6",marks.length);

marks.forEach(function(mark){

       console.log('Pass status is '+(mark>=passingMark));

   })

}

totalMarks(90,99,87,98,88)

/*Output : Pass status is true

a12.html:48 Pass status is false

a12.html:48 Pass status is true

a12.html:48 Pass status is false*/

</script>

 

Site Footer