Thursday, December 18, 2008

varargs in javascript

I'm learning Javascript in my spare time. So when I learnt the possibility of using varargs in Javascript, I wanted to share it. Here we go;

You probably know how functions are defined in Javascript:

1function transform(){
2     // write stuff to html below
3     document.write("transform function initiated");
4}


It is, of course, possible to define functions with arguments such as;

1function transformWithMessage(message){
2     document.write("transform function initiated: "+message);
3}


Now, I'll show functions with indefinite number of arguments;

1// defined similarly to a function with no argument
2function transform(){
3     document.write("transform function initiated: ");
4// arguments array holds any argument sent to transform() function
5     for(var i=0; i< arguments.length; i++)
6      document.write(arguments[i]+" ");
7     }


A call such as transform("first lock engaged", "second lock engaged") will result in an output such as transform function initiated: first lock engaged second lock engaged . Similarly, a call such as transform("first", "second", "third") will result in an output such as transform function initiated: first second third .