Question

I have an if test in JavaScript which achieves what I want but not as elegantly as possible. It goes like this:

if (x > y || p < q) {
    // don't do anything
} else {
   doSomeFunction();
}

If there any way to flip the logic of this so there's only a single if statement without having to have a dummy if-condition as well as the else condition?

Was it helpful?

Solution

You can use the ! operator to invert the condition:

if (!(x > y || p < q)) {
   doSomeFunction();
}

Or simply rewrite the condition like this:

if (x <= y && p >= q) {
   doSomeFunction();
}

Note: See De Morgan's laws for an explanation about why these two conditions are equivalent.

OTHER TIPS

You can simply invert the comparisons and the logical OR.

if (x <= y && p >= q) {
    doSomeFunction();
}

Along with the other answer, the last option (less readable) is :

(x > y || p < q) || doSomeFunction();

If the left bracket is true, it will NOT execute the function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top