How to create a Javascript function that accepts an arbitrary number of arguments?

Posted on

Question :

Functions of type console.log are given any number of arguments. How do I specify this for a Javascript function?


Answer :

In Javascript, every function, regardless of the arguments specified in its signature, has a arguments object. This object contains all arguments passed to the function. But at first it is of type object , so it is common to do this to make it a type Array :

function minhaFuncao() {
  var args = [], 0);
  for (var i = 0; i < args.length; i++) console.log(args[i]);

minhaFuncao(1, 2, 3); // args = [1, 2, 3];

The code above calls the function slice of the protoripo of Array in arguments , returning a Array so we can use your objects more easily.

In cases when you want to have a fixed number of arguments, then variable arguments, just change the number passed as the second argument to :

function minhaFuncao(x, y) {
  var args = [], 2);
  for (var i = 0; i < args.length; i++) console.log(args[i]);

minhaFuncao(1, 2, 3, 4, 5); // x = 1, y = 2, args = [3, 4, 5];


A more sensible approach is to map out arguments:

function DoSomething(config) {
   config = config || {};
   var idioma = config.Idioma || "en-GB";

The first line initializes an empty map if the function has been called without arguments: DoSomething();

The function can be called this way:

DoSomething({ idioma : "pt-PT", outraChave: "outro valor" });

This approach has 2 advantages:

  • You can name the arguments, making it easier to keep the code over time;
  • As the processing depends on the name of the arguments, and not on your order , we can simply omit values – instead of calling the function with% p>

    For example

    Let’s say the function expects 4 arguments null , instead of:

    DoSomething(null, null, null, "ola");

    We would use:

    DoSomething({arg4: "ola"});

Several methods of jQuery libraries use this approach to pass a set of configuration data.


An example:

function somar() {
    var resultado = 0;

    for (var i = 0, len = arguments.length; i < len; i++) {
        resultado += arguments[i];
    return resultado;

console.log(somar(1, 1, 1, 3, 3, 1, 5, 8, 7)); // = 30

console.log(somar(1, 1, 1)); // = 3

That is, just use the special variable arguments for each argument passed to the function. Being arguments[0] the 1st argument, arguments[1] the 2nd argument, and so on.


Leave a Reply

Your email address will not be published. Required fields are marked *