6

I want to be able to do this in JavaScript:

function myFunction(one, two = 1) {
     // code
}

myFunction("foo", "2");

myFunction("bar");

I tried this and it doesn't work. I don't know how to call this type of parameters, could somebody point me in the right direction?

Thanks.

Angelo A
  • 2,394
  • 5
  • 23
  • 36
  • 1
    Answers involving the `two = two || x;` pattern should be understood as risky, depending on your situation. It means to override *any* "falsy" value of the parameter with the default value, which may or may not be appropriate. – Pointy Oct 28 '12 at 17:10

4 Answers4

3
function foo(a, b)
 {
   a = typeof a !== 'undefined' ? a : 42;
   b = typeof b !== 'undefined' ? b : 'default_b';
   //...
 }

Possibly duplicate of Set a default parameter value for a JavaScript function

Community
  • 1
  • 1
Mihai Matei
  • 22,929
  • 3
  • 29
  • 46
  • definite duplicate...but you *do* want to check explicitly for undefined as in this answer – Matt Whipple Oct 28 '12 at 17:09
  • Because `typeof` returns the type of the parameter you gave.. if `a` is a string then `string` is returned and if there is no parameter then the typeof will return `undefined` – Mihai Matei Oct 28 '12 at 17:15
  • If you think this is a duplicate, you should vote to close or flag it as such. Don't copy the answer here. – Felix Kling Oct 28 '12 at 18:00
2
function myFunction(one, two) {
     two = two || 1
}

To be more precise e.g. it may not work when two is zero, check for null or undefined e.g.

if (typeof two === "undefined") two = 1
Anurag Uniyal
  • 77,208
  • 39
  • 164
  • 212
2

Use this :

function myFunction(one, two) {
   if (typeof two == 'undefined') two = 1;
   ...
}

Beware not to do the common mistake

two = two || 1;

because this wouldn't allow you to provide "" or 0.

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
0

Try:

if ( typeof two === "undefined" ) two = 2;

or

two = typeof two !== "undefined" ? two : 2;

Undefined arguments will have the value undefined, which is a "falsy" value. We can test this falsyness, and change the value accordingly.

0x499602D2
  • 87,005
  • 36
  • 149
  • 233