简体   繁体   中英

Is there a better way to deal with default true?

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?

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM