Georgio
Georgio

Reputation: 73

invert a boolean expression

I have some code like this

var a = returnsABoolean();
var b = returnsABoolean();

if (!a || !b) {

} else {
  doStuff();
}

How would I invert the test in the if-statement such that I can rewrite this as

var a = returnsABoolean();
var b = returnsABoolean();

if (someExpression) {
  doStuff();
}

In other words, what test should I replace someExpression with to preserve the existing behaviour?

Upvotes: 4

Views: 8591

Answers (3)

Collin Graves
Collin Graves

Reputation: 2257

Simply assign the logical inverse of your conditional to your previous scope's "else" statement.

if( a && b ) { 
    doStuff();
     }

Upvotes: 1

slebetman
slebetman

Reputation: 113866

You need to apply De Morgan's theorem. Which states:

!A || !B == !(A && B)

Therefore your test can be re-written as:

if (a && b) {
    doStuff();
}

Why does it work?

Basically, applying De Morgan's theorem you first rewrite your statement as:

if ( ! (a && b) ) {

} else {
    doStuff();
}

Since we now want to invert !(a&&b) we simply remove the not:

if ( (a && b) ) {
    doStuff();
}

Upvotes: 10

Brennan
Brennan

Reputation: 5732

De Morgan's law states that you can rewrite !a || !b as !(a&&b)

This also works the other way: !a && !b can be rewritten as !(a||b)

Upvotes: 1

Related Questions