3

I have little experience in javascript but in other programming languages the following is possible, to set a default value for a missing parameter in a function.

For instance lets say i have a function

function foo(a , b)
  return a + b 
{

I would like to be able to call the above function with 1 parameter or with 2 parameters

one parameter case:

foo(2)   //a =2 and b would be automatically set to a default no argument value,

two parameter case:

foo(1,2)  // a = 1 , b = 2 => 3

Is this possible in javascript that is IE 8 compatible or using Jquery 1.7.2?

pyCthon
  • 11,746
  • 20
  • 73
  • 135

5 Answers5

6

JavaScript functions allow you to call them with less parameters than specified.

What you're trying to accomplish is possible doing something like the following:

function foo(a , b){
  if(typeof b === "undefined"){
      b=3;
  }
  return a + b; 
}
foo(5);//return 3;

I strongly suggest that you check for undefined and not rely on the || operator. I've spent hours debugging code that made that assumption and failed when passing 0 or another falsy value. The JavaScript type system can get really tricky, for example "0" is falsy.

ECMAScript Harmony (the next version) allows default parameters like in those other languages using the following syntax

function foo(a , b=3){
  return a + b;
}

This does not work in IE8 like the first version though.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
3

Yes, it's possible. If a parameter isn't passed, you get a special value "undefined". The following works for me:

function foo(a, b) {
  a = a || defaultForA;
  b = b || defaultForB;

}

Due to the way Javascript treats conversion to boolean, the following will all be considered undefined in the above code snippet:

undefined
null
0
"" (empty string)
false

So if those values are important to you, you'll need to explicitly test for undefined rather than the blanket "if not false" test being used above.

Chris Tavares
  • 29,165
  • 4
  • 46
  • 63
3

No, but you can simulate this effect manually with a tertiary operator or an if statement (just make sure you check for undefined!):

function foo(a, b) {
    b = (typeof b === "undefined") ? 2 : b;

    return a + b;
}
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
2

An undefined parameter evaluates as false, so you can do something like this in the beggining of your function foo:

a = a || 0;
b = b || 0;

That way if a or b exist, they will be evaluated with their own values and with 0 otherwise.

2

You can just test if you received a parameter:

function foo(a, b) {
  if(typeof b === "undefined") {b = 2;}
}

By testing for "undefined" you can also accept parameters that evaluate to false (like null or "" or 0 or false)

Steve
  • 8,609
  • 6
  • 40
  • 54