JavaScript Quick Tips - default values
JavaScript does not have a mean to specify a default value for a function’s arguments. Fortunately, there is a quick way around this issue using the logic operator OR (i.e. ||).
function myFunction(arg) {
arg = arg || 'default value';
return arg;
}
myFunction('my string'); // returns 'my string'
myFunction(); // returns 'default value'
Watch out for the following though:
myFunction(''); // returns 'default value' too!;
As 0 or null, the empty string is evaluated as false and thus the function returns the default value rather then the expected empty string.
This is rarely an issue, but if it is, use this instead:
function myFunction(arg) {
if (arg === undefined) arg = 'default value';
return arg;
}
myFunction('my string'); // still returns 'my string'
myFunction(); // still returns 'default value'
myFunction(''); // now correctly returns an empty string (i.e. '')
Comments
-
make a helper funktion:
function setDefaultValue( arg , defaultValue) { if (typeof arg == ‘undefined’){ return defaultValue; } else { return arg; } }
then use it:
function myFunction(arg) { arg = setDefaultValue( arg , ‘default value’);
// mycode}
Tue, March 06 at 13:44 PM