Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I easily set a variable to false with a default of true?

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?

like image 784
user2251919 Avatar asked May 08 '13 13:05

user2251919


2 Answers

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
like image 124
Ian Avatar answered Nov 15 '22 18:11

Ian


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;
like image 41
epascarello Avatar answered Nov 15 '22 17:11

epascarello