Default argument values in JavaScript functions

Douglas Crockford picture Douglas Crockford · Jun 26, 2011 · Viewed 211k times · Source

Possible Duplicate:
How do I make a default value for a parameter to a javascript function

in PHP:

function func($a = 10, $b = 20){
  // if func() is called with no arguments $a will be 10 and $ b  will be 20
}

How can you do this in JavaScript?

I get a error if I try to assign values in function arguments

missing ) after formal parameters

Answer

Ravan Scafi picture Ravan Scafi · Jun 26, 2011

In javascript you can call a function (even if it has parameters) without parameters.

So you can add default values like this:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   //your code
}

and then you can call it like func(); to use default parameters.

Here's a test:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   alert("A: "+a+"\nB: "+b);
}
//testing
func();
func(80);
func(100,200);