Default Parameter Value in Javascript

Share this Article :


Like in Java, C++, PHP is there any way to use Default parameter value in Javascript? If so How to achieve it ?

The Answer for this Fantastic and Very useful question is YES. But unlike in other programming languages, we can achieve this in popularly two diff ways.

Usually The syntax for the Default Parameter Value would something similar to this

1
2
3
4
5
function   simpleInterest($principal, $rate, $time=2)
{
     return  ($principal*$rate*$time) / 100;
 
}

Here We can use The above function in following ways

1
2
3
4
5
 //  Calling the function with out the Third  Param, In this  case  the  Function will automatically assigns 2 to $time
simpleinterest(150000,5);
 
 //  Calling the function with the Third  Param, In this  case  the  Function wont  assigns 2 to $time
simpleinterest(150000,5,5);

Here is workaround for this in javascript :

We can Achieve The same functionality in Javascript Mainly in Two Ways

Type 1 :

Pass the Required number of arguments, Check The Parameter with Null If it is Null then Assign the Default value

1
2
3
4
5
6
7
8
9
10
// Javascript  Function
function  simpleinterest(principal,rate,time)
{
//  Here is  the  Way  Starts
//  Check  weather  the param  is null or not,  If  null  then  assign  Default  value
if (time == null)
time=2  // Defualt  Value 
 
return  (principal*rate* time) /100;
}

Type 2 :

Play with the Arguments and Arguments.length

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Javascript  Function
function  simpleinterest()
{
//  Here is  the  Way  Starts
//  Do not  Pass any  args  to the function.  Make use  of  arguemtns  and  arguments.length  function  like follows
if (arguments.length == 2)
{
time=2  // Defualt  Value
principal = arguments[0];
rate=arguments[1];
} 
 
if (arguments.length == 3)
{
principal = arguments[0];
rate=arguments[1];
time=arguments[2];
} 
 
//  This   Show Stopper   Should  be there  according to your  Needs,
//  In the  Current  Function   if   we are passing  only one parameter  or  no parameter   The function  should  not work  so,  simply  return falsel
if  (arguments.length<2)
return  false;
 
//  If  everything is  set  then   calculate  
 
return  (principal*rate* time) /100;
}

Hope This article Guided you with your Requirement ..

Written by adrevol

{adrevol has written 91 posts on ITTreats.com . See all posts by }


Leave a Reply