user2251919 user2251919 - 1 year ago 97
Javascript Question

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;

is either true or false, and in this case
will always be true because if
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?

Ian Ian
Answer Source

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"


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download