Is it possible to get all arguments of a function as single object inside that function?


Is it possible to get all arguments of a function as single object inside that function?

In PHP there is func_num_args and func_get_args, is there something similar for JavaScript?


Solution 1:

Use arguments. You can access it like an array. Use arguments.length for the number of arguments.

Solution 2:

The arguments is an array-like object (not an actual array). Example function…

function testArguments () // <-- notice no arguments specified
    console.log(arguments); // outputs the arguments to the console
    var htmlOutput = "";
    for (var i=0; i < arguments.length; i++) {
        htmlOutput += '<li>' + arguments[i] + '</li>';
    document.write('<ul>' + htmlOutput + '</ul>');

Try it out…

testArguments("This", "is", "a", "test");  // outputs ["This","is","a","test"]
testArguments(1,2,3,4,5,6,7,8,9);          // outputs [1,2,3,4,5,6,7,8,9]

The full details:

Solution 3:

ES6 allows a construct where a function argument is specified with a “…” notation such as

function testArgs (...args) {
 // Where you can test picking the first element

Solution 4:

The arguments object is where the functions arguments are stored.

The arguments object acts and looks like an array, it basically is, it just doesn’t have the methods that arrays do, for example:

Array.forEach(callback[, thisArg]);[, thisArg])

Array.filter(callback[, thisArg]);

Array.slice(begin[, end])

Array.indexOf(searchElement[, fromIndex])

I think the best way to convert a arguments object to a real Array is like so:

argumentsArray = [].slice.apply(arguments);

That will make it an array;


function ArgumentsToArray(args) {
    return [].slice.apply(args);

(function() {
   args = ArgumentsToArray(arguments);

   args.forEach(function(value) {
      console.log('value ===', value);

})('name', 1, {}, 'two', 3)


> value === name
> value === 1
> value === Object {}
> value === two
> value === 3

Solution 5:

You can also convert it to an array if you prefer. If Array generics are available:

var args = Array.slice(arguments)


var args =;

from Mozilla MDN:

You should not slice on arguments because it prevents optimizations in
JavaScript engines (V8 for example).

Solution 6:

As many other pointed out, arguments contains all the arguments passed to a function.

If you want to call another function with the same args, use apply


var is_debug = true;
var debug = function() {
  if (is_debug) {
    console.log.apply(console, arguments);

debug("message", "another argument")