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:


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


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


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


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


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


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 .

No comments:

Post a Comment