Thursday, May 23, 2024
142
rated 0 times [  145] [ 3]  / answers: 1 / hits: 9168  / 10 Years ago, wed, april 9, 2014, 12:00:00

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?


More From » if-statement

 Answers
9

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.


[#46167] Tuesday, April 8, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bobbidayanam

Total Points: 82
Total Questions: 99
Total Answers: 96

Location: Venezuela
Member since Sat, Apr 24, 2021
3 Years ago
;