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".





No comments:

Post a Comment