In some languages you can set default values for function\'s arguments:
function Foo(arg1 = 50, arg2 = \'default\') {
//...
}
How do yo
In JavaScript, anything that isn't set is given the value undefined
. This means that if you want to set default values for a function, your first line needs to be a check to see if those values aren't defined:
function Foo(arg1, arg2) {
if (typeof(arg1) === "undefined") { arg1 = 50; }
if (typeof(arg2) === "undefined") { arg2 = "default"; }
}
You can take a bit of a short cut if you know roughly what those values will be:
function Foo(arg1, arg2) {
arg1 = arg1 || 50;
arg2 = arg2 || "default";
}
However, if those arguments are falsy, they'll be replaced. This means that if arg1 is an empty string, null
, undefined
, false
or 0
it'll be changed to 50, so be careful if you chose to use it