Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript simplify conditional expression to something more readable

Tags:

javascript

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?

like image 676
danday74 Avatar asked Aug 14 '26 15:08

danday74


1 Answers

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
like image 168
Nina Scholz Avatar answered Aug 17 '26 04:08

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!