JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to use arguments object in JavaScript Function?

Every JavaScript function has arguments object that stores the argument values passed to the function. The arguments object is an array-like object with a length property that returns the total number of arguments passed to the function.

The arguments object follows zero-based indexing, so the first argument is at 0th position, the second argument is at 1st position, and so on. You can access arguments passed to the function using the square brackets notation.

function show(a, b){
  console.log(arguments);
  console.log("First argument is " + arguments[0]);
  console.log("Second argument is " + arguments[1]);
  console.log("Third argument is " + arguments[2]);
}

show('red', 'blue', 'green');

Output

{
  0: "red",
  1: "blue",
  2: "green"
}
First argument is red
Second argument is blue
Third argument is green

Even though you can specify parameters to the function, you have to use the arguments object to handle a variable number of arguments.

Note: The arguments object is not available in arrow functions.

The arguments objects is used for writing varargs function. In simple terms, the arguments object is used to write a function that accepts a variable number of arguments.

Also, ES6 has introduced a new operator called the rest parameter, using which you can also write a function that accepts any number of arguments.

Let's learn how to use the arguments object with the help of examples.

Suppose you want to calculate the sum of all the arguments passed to the function. For this, you have to write the sum() function like this

function sum(a, b){
  let add = 0;
  for(let i=0; i< arguments.length; i++){
    add += arguments[i];
  }
  return add;
}

console.log(sum(1,2)); //3
console.log(sum(1,2,3)); //6
console.log(sum(1,2,3,4)); //10

In another example, the max() function is created to return the highest value among the arguments passed to the function.

function max(){
  let maximum = arguments[0];
  for(let i=1; i< arguments.length; i++){
    if(arguments[i] > maximum){
      maximum = arguments[i];
    }
  }
  return maximum;
}

console.log(max(23, 10, -4, 91, 57, 31)); //91

Recommended Posts