This question already has an answer here:
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?
The test for undefined is unnecessary and isn't as robust as it could be because, as user568458 pointed out, the solution provided fails if null or false is passed. Users of your API might think false or null would force the method to avoid that parameter.
The result is:
Those last two are potentially bad. Instead try:
Which results in:
The only scenario where this isn't optimal is when you actually have optional parameters that are meant to be booleans or intentional null.
Here is my solution. With this you can leave any parameter you want. The order of the optional parameters is not important and you can add custom validation.
I am used to seeing a few basic variations on handling optional variables. Sometimes, the relaxed versions are useful.
The falsy default used with variable
a
is, for example, used extensively in Backbone.js.Similar to Oli's answer, I use an argument Object and an Object which defines the default values. With a little bit of sugar...
...this can be made a bit nicer.
What's nice about this method?
undefined
when, say there are 5 arguments and you only want to customise the last one, as you would have to do with some of the other methods suggested.CharField
callsField
's constructor).Folks -
After looking at these and other solutions, I tried a number of them out using a snippet of code originally from W3Schools as a base. You can find what works in the following. Each of the items commented out work as well and are that way to allow you to experiment simply by removing individual comments. To be clear, it is the "eyecolor" parameter that is not being defined.
In ECMAScript 2015 (aka "ES6") you can declare default argument values in the function declaration:
More about them in this article on MDN (despite the article title, they're called "arguments," not "parameters," in JavaScript).
This is currently only supported by Firefox, but as the standard has been completed, expect support to improve rapidly.