Inverting if Clause in JavaScript Fails

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?

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. In your final example, the “do something” block will execute if a is any of the following: undefined, null, 0, “0”, “”, or false.

    If that’s really your intent, a more standard blanket approach for such an “if” might be:

    if (!a) {
    // do something
    }

    If instead you need more specificity, you can of course make use of !== and ===

Your Comments

*

Protected with IP Blacklist CloudIP Blacklist Cloud

Follow

Get every new post delivered to your Inbox

Join other followers: