最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I easily set a variable to false with a default of true? - Stack Overflow

programmeradmin4浏览0评论

I usually set object properties like so,

// Boolean
this.listening = config.listening || true;

But config.listening is either true or false, and in this case this.listening will always be true because if config.listening is false it will equal true.

Is there a better way to set these boolean properties without having to do an if statement?

Is there a if isset function in javascript to check it exists rather than what it equals to?

I usually set object properties like so,

// Boolean
this.listening = config.listening || true;

But config.listening is either true or false, and in this case this.listening will always be true because if config.listening is false it will equal true.

Is there a better way to set these boolean properties without having to do an if statement?

Is there a if isset function in javascript to check it exists rather than what it equals to?

Share Improve this question asked May 8, 2013 at 13:32 user2251919user2251919 6752 gold badges11 silver badges23 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

You could use the ternary (conditional) operator like this:

this.listening = config.listening === false ? false : true;

If config.listening is false, this.listening is set to false. If it's any other value, it's set to true.

If you want to check if it's defined, you could use:

this.listening = typeof config.listening !== "undefined"

References:

  • https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator

You need to check to make sure it is not undefined, not that it is a "falsey" value.

this.listening = config.listening!==undefined ? config.listening : true;
发布评论

评论列表(0)

  1. 暂无评论