Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pre-defined parameters [duplicate]

Tags:

javascript

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.

like image 637
Angelo A Avatar asked Oct 28 '12 17:10

Angelo A


3 Answers

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

like image 191
Mihai Matei Avatar answered Nov 18 '22 02:11

Mihai Matei


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.

like image 29
Denys Séguret Avatar answered Nov 18 '22 03:11

Denys Séguret


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
like image 2
Anurag Uniyal Avatar answered Nov 18 '22 03:11

Anurag Uniyal