Friday, July 29, 2011

All about function arguments

JavaScript allows a variable number of arguments to be passed into a function.  Thats actually a pretty cool feature that some languages (Java) have only added in the last few versions.  Lets look at it a little more by examining a function that takes two numbers and returns the sum:

function sum(firstNum, secondNum) {
return firstNum + secondNum;
}

We can call this function like this:

// Will return 14
sum(3, 11); 

But we are allowed to pass as many arguments to the function as we want:

// Will still return 14
sum(3, 11, 4, 99, 0, 2);

No errors are thrown, however the function only adds the first two numbers, as we coded it to do.  How can we take advantage of a variable number of arguments?  This is where the arguments object comes in.  It is available to you any time you are executing code within a function.  Its an array like object that contains each of the arguments that were passed to the current function.  Not just the declared parameters... but everything that was actually passed at call time.

Lets see how we can make our sum function work better using the arguments object:

function sum() {
var runningTotal = 0;
for (var i = 0; i < arguments.length; i++) {
runningTotal += arguments[i];
}
return runningTotal;
}

We now loop through each of the arguments adding them in turn.

// Will return 14
sum(3, 11);


// Will return 119
sum(3, 11, 4, 99, 0, 2);

So now that we can determine our arguments at call time, is there an easy way to find out (with code) how many declared parameters a function is expecting?  Yup.  Simply check the length property of the function.  Example:

function takesThree(x, y, z) {}
console.log(takesThree.length);
--> 3


function takesOne(first){}
console.log(takesOne.length);
--> 1

function takesNone(){}
console.log(takesNone.length);
--> 0


No comments:

Post a Comment