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?
If you're using defaults extensively, this seems much more readable:
Just declare this function on the global escope.
Usage pattern
fruit = defaultValue(fruit,'Apple');
*PS you can rename the
defaultValue
function to a short name, just don't usedefault
it's a reserved word in javascript.You can use some different schemes for that. I've always tested for arguments.length:
-- doing so, it can't possibly fail, but I don't know if your way has any chance of failing, just now I can't think up a scenario, where it actually would fail ...
And then Paul provided one failing scenario !-)
Those ones are shorter than the typeof operator version.
If you need to chuck a literal
NULL
in, then you could have some issues. Apart from that, no, I think you're probably on the right track.The other method some people choose is taking an assoc array of variables iterating through the argument list. It looks a bit neater but I imagine it's a little (very little) bit more process/memory intensive.
If you're using the Underscore library (you should, it's an awesome library):
This is what I ended up with:
Called like this: