danday74
danday74

Reputation: 56946

JavaScript simplify conditional expression to something more readable

Here's my code:

if (!(a === false && b === true)) {
  // do something
}

Here's a truth table for my expression:

a      b      !(a === false && b === true)
false  false  true
false  true   false
true   false  true
true   true   true

The expression !(a === false && b === true) is a bit of a mouthful, how would I simplify this in JavaScript?

Upvotes: 3

Views: 516

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could take

a || !b

instead.

const
    fn = (a, b) => a || !b;

console.log(fn(false, false)); //  true
console.log(fn(false, true));  // false
console.log(fn(true, false));  //  true
console.log(fn(true, true));   //  true

The result takes only boolean values and De Morgan's laws:

!(a && b) = !a || !b 
!(a || b) = !a && !b

Upvotes: 8

Related Questions