Javascript Functions


Javascript functions have some interesting features

If the function is not anonymous then it is stored in a variable having the name as the function
For example:

function addStuff(num1, num2){
return num1+num2;
}

alert(addStuff);
The output is the body of the function

alert(addStuff.length);
The output is the number of named arguments, as in 2 for the above function (num1, num2)

Javascript functions doenot require named arguments. Every function has an available property called arguments which is an array like object(as in does most things an array can).

Javascript functions don’t throw a tantrum when they are provided with less or more arguments. So using named arguments is not a required.

Below is a general function to add arguments provided to the function(it does not have any named arguments):

function addStuff(){
var len=arguments.length;
var addSum=0;
var x=0;
while(x<len){
if(!isNaN(arguments[x])){
addSum=addSum+parseFloat(arguments[x]);
}
x++;
}
if(isFinite(addSum)){
return addSum;
}
else{
return 0;
}
}

alert(addStuff(1));
alert(addStuff(1,2));
alert(addStuff(1,2,3));
alert(addStuff(1,2,3, ‘a’, 4.5,5));
alert(addStuff(1,2,3, Number.MAX_VALUE, 4.5,Number.MAX_VALUE));

The function does some very simple stuff. It uses a counter and add numbers which are provided in the function invocation.

  1. Check the length of the arguments array
  2. Transverse through the array
  3. Add any valid number, after checking whether it is a number and converting it to float. If the argument is not a number, it ignores it. The parseFloat is required for this reason that ’20.5′ is treated as a 20.5 rather than string (which will cause concatenation).
  4. If the result is finite, return it, else return a 0.
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: