Sunday 29 April 2012

Default Arguments in Javascript

I don't know why javascript do not support default arguments. They should add that. Anyhow there is a another way to perform the same operation. Here is an example
In other languages we pass default arguments like this
int function( var=value,var=value)

We don't have this facility in Javascript so we length of code increases a bit. We can do the same by following method.

function sum(a1,b1)
{
a1=a1?typeof a1=="undefined": default-value;
//meaning
//if the type of variable a1 is undefined that means that the user has not passed any value so we can assign
//our own default value.
typeof operator in javascript returns a string telling the type of variable

for eg:
var abc="Piyush";
alert(typeof abc);
this will return string signifying that the variable is string.

It is very simple.
Happy Coding.

No comments:

Post a Comment