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?
With ES2015/ES6 you can take advantage of
Object.assign
which can replace$.extend()
or_.defaults()
You can also use defaults arguments like this
I don't know why @Paul's reply is downvoted, but the validation against
null
is a good choice. Maybe a more affirmative example will make better sense:In JavaScript a missed parameter is like a declared variable that is not initialized (just
var a1;
). And the equality operator converts the undefined to null, so this works great with both value types and objects, and this is how CoffeeScript handles optional parameters.Though, there are concerns that for the best semantics is
typeof variable === 'undefined'
is slightly better. I'm not about to defend this since it's the matter of the underlying API how a function is implemented; it should not interest the API user.I should also add that here's the only way to physically make sure any argument were missed, using the
in
operator which unfortunately won't work with the parameter names so have to pass an index of thearguments
.http://jsfiddle.net/mq60hqrf/