Reputation: 764
First I tried this:
var coolFunc = function(options) {
var minNum = options.minNum || true,
// rest of the function
}
But that can never result in false as the value for the minNum var.
So now I am doing this:
var coolFunc = function(options) {
var minNum = options.minNum;
if (minNum === undefined) minNum = true;
// rest of the function
}
Is there a more standard way of doing this?
Upvotes: 2
Views: 77
Reputation: 382150
That's the right way.
A common variant is
var coolFunc = function(options) {
var minNum = "minNum" in options ? options.minNum : true;
// rest of the function
}
Personally I sometimes use a utility function:
function opt(options, key, defaultValue) {
if (options && key in options) return options[key];
return defaultValue;
};
so that my functions are like this:
var coolFunc = function(options) {
var minNum = opt(options, "minNum", true);
// rest of the function
}
A small advantage is that it also checks that options
isn't undefined
.
but it's not a big gain, especially when you don't expect falsish values, so most often I don't care.
Upvotes: 3
Reputation: 74
This variant might be more straight forward than the ternary suggestions:
var minNum = (typeof options.minNum !== 'boolean') || options.minNum;
or
var minNum = (! "minNum" in options) || options.minNum;
Upvotes: 0