Javascript Rest Operators and the “arguments” Variable

javascript rest operator and the argument variable
read about javascript rest operator and the argument variable

This article is all about javascript rest operators and how it could be used in javascript programming. A little discussion is also included for the arguments variable and how to process it inside a function.

Have you ever thought of how some Javascript built-in functions like Math.max() contain multiple arguments? Yes, it is possible – javascript functions may have an arbitrary number of arguments.

This is made possible with the javascript rest operators and it looks like this:

function getSum(...addends) {
  let sum = 0;
  for (let addend of addends) sum += addend;
  return sum;
}

alert( sumAll(1) ); // 1
alert( sumAll(1, 2) ); // 3
alert( sumAll(1, 2, 3) ); // 6

As you see in the function’s argument, we added three dots before our argument: addends. The three dots (…) also called the rest operator tells the function to merge the arguments in the function into an array.

In the function, we can then process the inputs similar to how we process arrays.

We must follow some rules though when we use rest operators. For example, it is not possible to place the rest operator at the first or middle part if your function has multiple arguments.

function person(...arguments, firstname, lastname) {
//the argument arrangement above does not make sense...
}

The above function does not make sense. So we must arrange the arguments like this:

function person(firstname, surname, ...args){
//this is clearer and this will work
}

Simply put: we must place the rest operator as the last argument.

The arguments variable

Another useful javascript trick is not placing arguments in the function. We may then process all inputs though with the argument variable. The argument variable is an array and we can process it like how we treat arrays. For example:

function testing(){
  for(var args of arguments){
    //arguments is the variable fed to testing function
    console.log(arg); //lets just output each argument
  }
}

testing('a','b');
testing('a','b','c');

However, creating functions like this would result in readability problems. The reason is that we don’t know what inputs we’re feeding our function. The arguments variable though is NOT really an array such that Array.map() may not work.

Another problem is: arguments can not be used with arrow functions. This will NOT work:

const arrowfunc = () => {
  for(var arg of arguments){
    console.log(arg);
  }
}

Take note that arrow functions cannot have their own this. They can not have their own arguments variable also.

Please follow and like us:
error