Skip to content

Inverting if Clause in JavaScript Fails

Updated: at 06:34 PM

I think I must have once know this but totally forget and it bit me today.  Often, when I’m thinking through logic, I can figure something out in the positive, then simply invert it to get the negative.  That is, if I know the following if statement:

if (a == 1 && b == 2) {
  // do something
}

Then, it follows that the reverse is:

if (a != 1 || b != 2) {
  // do something
}

So, when testing for undefined in JavaScript I had this:

if (a != undefined && a != 0) {
  // do something
}

which worked, but when I inverted it to

if (a == undefined || a == 0) {
  // do something
}

it failed.

Reason is because the second part of the if needs to get evaluated.  So, my answer to fix it is this:

if (!(a != undefined && a != 0) ){
  // do something
}

Anyone care to add to this?