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?

Solutions/Answers:

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: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments

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
 console.log(args[0]); 
}

Solution 4:

The arguments object is where the functions arguments are stored.

Related:  How to select the first element in the dropdown using jquery?

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]);

Array.map(callback[, 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;

reusable:

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

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

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

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

result:

> 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)

Otherwise:

var args = Array.prototype.slice.call(arguments);

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.

Related:  Pagination: Server Side or Client Side?

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

Example:

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

debug("message", "another argument")