Passing unknown number of arguments to a function in Javascript

JavascriptObject Oriented ProgrammingFront End Technology

When you call a function in JavaScript you can pass in any number of arguments. There is no function parameter limit. This also means that functions can't be overloaded in traditional ways in js.

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.

For example, if a function is passed 3 arguments, you can access them as follows −

arguments[0] // first argument
arguments[1] // second argument
arguments[2] // third argument

Note − arguments is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have Array's built-in methods like forEach() and map().

For example, to accept a arbitrary number of args, you can create a function as follows −


function printAllArguments(a, b) {
   console.log("First arg: " + a)
   console.log("Second arg: " + b)
   console.log("All args: " + arguments)
printAllArguments(1, "hello")
printAllArguments(1, "hello", 1, "hello")


First arg: 1 
Second arg: undefined 
All args: {"0":1}
First arg: 1
Second arg: hello 
All args: {"0":1,"1":"hello"} 
First arg: 1
Second arg: hello 
All args: {"0":1,"1":"hello","2":1,"3":"hello"} 
Published on 16-Sep-2019 10:45:18