How can I easily set the variable to false with the default value true?

I usually set the properties of an object so that

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

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

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

Is there an ifset function in javascript to test it, and not that it is equal?

+6
source share
3 answers

You can use the ternary (conditional) operator as follows:

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

If config.listening is false , this.listening set to false . If this is a different value, it is set to true .

If you want to check if this is defined, you can use:

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

Literature:

+12
source

You need to check to make sure that it is not undefined, and not that it is a β€œfalse” value.

 this.listening = config.listening!==undefined ? config.listening : true; 
+3
source

The fastest way is this.

 d = true; 

d returns true.

Then just use it! operator to switch the boolean from true to false.

 d = !d; 

d returns false.

Then again and again.

 d = !d; 

d returns true.

-1
source

Source: https://habr.com/ru/post/944528/


All Articles