Showing posts with label Advanceed-Rest parameters .... Show all posts
Showing posts with label Advanceed-Rest parameters .... Show all posts

Monday, April 16, 2018

The “arguments” variable

Actually rest parameters are available from ES6 on wards only. So if you you want the same behavior of Rest parameters in older than ES6, you should use "arguments".

Below example may tell you more clearly.


function showName() {
  alert( arguments.length );
  alert( arguments[0] );
  alert( arguments[1] );

  // Iteration also possible here
  // for(let arg of arguments) alert(arg);
}

// 2, Test1, Test2
showName("Test1", "Test2");

// 1, Ilakiya, undefined (Because no second argument)
showName("Ilakiya");

From the above code, we are calling showName method twice. While calling at first time we are passing two parameters.  So length is 2 and alert showing two parameters.

But while calling second showName function, we are passing only one parameter. So that , alert showing length as 1 and second parameter as undefined. Hope you got it.

Things to Remember:
              1. arguments is like an array , but it will not support array method . So you cannot use arguments.map() with this.

              2. Arrow functions do not have "arguments".





Rest parameters ...


A function can be called with any number of arguments. What is this means? Assume that you one simple sum function which accept two parameters. So you can pass those two parameters easily. But Suppose if it is more than 5 parameters or more than 10 parameters. You will get lazy to pass manually, right ? To avoid that use rest parameter.

Simple Example I:
function sumAll(...args) { // args is the name for the array
  let sum = 0;

  for (let arg of args) sum += arg;

  return sum;
}

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

The rest parameters should be mentioned as three dots .... Here ...args is array which have all of your arguments.

Suppose if you dont want all n parameters as ...args, you can give first two as manual and remainig all as ...args.

Simple Example II:

function showName(firstName, lastName, ...titles) {
  alert( firstName + ' ' + lastName ); // TestFirstName TestLastName

  // the rest go into titles array
  // i.e. titles = ["ArrayFirst", "ArraySecond"]
  alert( titles[0] ); // ArrayFirst
  alert( titles[1] ); // ArraySecond
  alert( titles.length ); // 2
}

showName("TestFirstName", "TestLastName", "ArrayFirst", "ArraySecond");


Note: Remember, the ...rest must always be last.