How to use arguments object In Javascript

While JavaScript does not have native support for variadic functions. The arguments object is available inside every function and allows you to access all arguments passed to the functions. Even arguments do not declare explicitly in function. An argument object is like an array of arguments of functions.

Example: Creating a variadic function using an argument object

Javascript




function SumOfNum() {
    let total = 0
    for (let i = 0; i < arguments.length; i++) {
        total += arguments[i]
    }
    return total;
}
  
console.log("Sum is ", SumOfNum(1, 2, 3, 4));
console.log("Sum is ", SumOfNum(1, 2, 5));


Output

Sum is  10
Sum is  8

Variadic Functions in JavaScript

JavaScript variadic function is a function that can accept any number of arguments. In variadic functions no predefined number of function arguments is present that’s why a function can take any number of arguments. Also, there are some inbuilt functions in JavaScript that are variadic e.g.: min and max functions.

Syntax

function NameOfFun( x1, x2, x3, ... ){
// function body
}

There are a few approaches by using these you can create variadic functions in javascript:

  • Using argument object
  • Using rest parameter

Similar Reads

Using arguments object

While JavaScript does not have native support for variadic functions. The arguments object is available inside every function and allows you to access all arguments passed to the functions. Even arguments do not declare explicitly in function. An argument object is like an array of arguments of functions....

Using Rest parameter

...