Is there a better way to do optional function parameters in JavaScript? [duplicate]
I've always handled optional parameters in JavaScript like this:
function myFunc(requiredArg, optionalArg){
optionalArg = optionalArg || 'defaultValue';
// Do stuff
}
Is there a better way to do it?
Are there any cases where using ||
like that is going to fail?
Solution 1:
Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative
if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }
Or an alternative idiom:
optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;
Use whichever idiom communicates the intent best to you!
Solution 2:
In ECMAScript 2015 (aka "ES6") you can declare default argument values in the function declaration:
function myFunc(requiredArg, optionalArg = 'defaultValue') {
// do stuff
}
More about them in this article on MDN.
This is currently only supported by Firefox, but as the standard has been completed, expect support to improve rapidly.
EDIT (2019-06-12):
Default parameters are now widely supported by modern browsers.
All versions of Internet Explorer do not support this feature. However, Chrome, Firefox, and Edge currently support it.
Solution 3:
I find this to be the simplest, most readable way:
if (typeof myVariable === 'undefined') { myVariable = 'default'; }
//use myVariable here
Paul Dixon's answer (in my humble opinion) is less readable than this, but it comes down to preference.
insin's answer is much more advanced, but much more useful for big functions!
EDIT 11/17/2013 9:33pm: I've created a package for Node.js that makes it easier to "overload" functions (methods) called parametric.