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.
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
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With