Welcome Guest! (App Version 3.1)

websitnero logo name

Rest Operator

Rest Operator

Rest Operator is another entry with ES6 and is associated with function parameters just like default arguments. When you pass parameters to a function, rest operator can be used to combine them into a single array. This is very useful in case where the exact number of arguments that are passed to a function is not known or is flexible.

For example, lets say that there is a function "alpha()" that returns the sum of all its arguments but the number of arguments passed can be 2,4 or 10 or any other number. The function should return the sum of all those arguments.

alpha = (...arr) => {
return arr.reduce((prev, current) => {
  return prev + current;
});
}
alpha(1,2,10,15); //this returns 28
alpha(10,8); //this returns 18
alpha(9,15,27); //this returns 51

Explaination: In the above example it does not matter how many arguments you pass to the function "alpha()", all the arguments are collected and put into an array named "arr". So, in the 3 cases above the arrays that are made are:

  • arr = [1, 2, 10, 15]
  • arr = [10, 8]
  • arr = [9, 15, 27]

Now, since whatever you are passing is converted into 1 single argument (arr array), therefore that can now easily be processed either using for loop (i < arr.length) or using 'reduce' function - that continues to iterate till there are items left in an array.

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.