Javascript Tutorial - Variadic Functions

Skill

Javascript Tutorial - Variadic Functions

Posted in:

A couple days ago, we took a look at how to write variable argument functions in C# using the params keyword. In that article, I mentioned that you can also write variable arity functions in javascript, but I didn't go into any detail as to how to do that. Well, now we are about to rectify that situation.

What is interesting with javascript is that you don't have to do anything special to make a function take a variable number of arguments. As we have noted before in other javascript tutorials, you can always leave arguments off the end of a javascript function call - the variables that refer to those arguments just end up being undefined. But you can also add arguments onto the end of a function call willy-nilly, and it won't affect anything at all.

For instance, the function below can be called with any number of arguments, and it will always work:

function funFunc(myArg)
{
  alert(myArg);
}

//Will alert 'undefined'
funFunc();

//Will alert 'Hi There!'
funFunc('Hi There!');

//Will alert 'Hi There'
funFunc('Hi There', 'Hi There Again');

Essentially, what happens here makes perfect sense. If you call the function with one argument, that value is assigned to the variable myArg and everything works out. If you call it with no arguments, nothing gets assigned to myArg, and so it ends up being undefined. And if you call the function with more than one argument, only the first value gets assigned to myArg, and the rest are left hanging out in the breeze.

But none of this answers the important question: how do you allow for truly variable number of arguments in javascript? Well, its really simple - you just access the arguments array. The arguments array is a special array that gets set when you enter a function call in javascript. The only thing special about it, though, is that it holds all the arguments that the function was called with - other than that it acts like a normal array. For instance:

function moreFun()
{
  var str = "";
  for(var i=0; i<arguments.length; i++)
  {
    if(i != 0)
      str += " ";
    str += arguments[i];
  }
  alert(str);
}

//Will alert ''
moreFun();

//Will alert 'Hi There!'
moreFun('Hi There!');

//Will alert 'Hi There Hi There Again'
moreFun('Hi There', 'Hi There Again');

<

Of course, you can mix and match using regualar arguments and the arguments array. For instance, here is a rendition of the fold function for javascript:

function fold(func)
{
  var result = 1;
  for(var i=1; i<arguments.length; i++)
  {
    result = func(result, arguments[i]);
  }
  return result;
}

var retVal = fold(function(a,b){ return a*b; }, 1, 3, 5, 7, 9);
//retVal holds 945

One thing to note here (and you might have already noticed) is that we start off from 1 in the arguments array for the fold function. This is because we already have a reference to argument 0 - it is assigned to func. So instead we fold from argument 1 onward, because those are the values we care about.

Also, the arguments array is not read only. This means that you can alter its contents, or even clear the array itself. For instance:

function messWithArgs(foo)
{
  var str = "Before: " + foo + " " + arguments[0] + "\n";
  arguments[0] = arguments[0] + 1;
  str += "After: " + foo + " " + arguments[0] + "\n";
  arguments = null;
  str += "After Nulling: " + foo + " " + arguments;
  return str;
}

retVal = messWithArgs(5);

//retVal now holds:
// Before: 5 5
// After: 6 6
// After Nulling: 6 null

So as you can see from that output, the variable in the arguments array is the same as the variable referred to as foo - changing one changes the other. And if you modify the arguments array itself (i.e, in this case set it to null), you loose the ability to access the arguments through the arguments array, but it doesn't affect any of the actual variables (as you can see, foo is still fine).

Well, that is it for variadic functions in javascript. Hopefully that clears up some questions on how javascript deals with function arguments. If it didn't, post your questions below and I'll take a stab at answering them.

Charitha
01/10/2008 - 23:17

Very nice explanation. Thanks

reply

The Reddest
08/21/2008 - 14:25

Sorry Garin, the comment system doesn't like < or > See this post on how to put code in the comments.

I'll delete your original post after you post a new one.

reply

Garin
08/22/2008 - 10:09

I have no question now. But may be trick below will useful for someone.
So, pass arguments from variadic function to another one:

function f1(/*any number of args*/)
{/*...*/}
function f1(/*any number of args*/
{
/*...*/
//call f1 with all args:
f1.apply(null, arguments);
/*...*/
}

reply

Anonymous
01/06/2012 - 12:39

Thank you for the tutorial.

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.