javascripttruthiness

Is //(typeof(myVar) != "undefined")// logically equivalent to the truthy //if (myVar)?


Over a large project I do a lot of exception handling by explicitly checking whether a variable has been set using typeof. It's a bit verbose and I'd like to change my habit to a simple truthy:

if (myVar) {//do stuff}

In the snippet below and in some other tests they appear to be equivalent. Before I doing sweeping code changes however (and replace hundreds of these) I'd like to confirm they're logically equivalent and learn about any edge cases that might get me.

//What I have been doing

let myVar;

{
//other code that may or may not be able to give myVar a value 
}

if (typeof(myVar) != "undefined"){
  console.log("the value has been set, do more stuff");
} else {
  console.log("the value was not set, handle the exception path");
}

//What I'd like to do

if (myVar) {
  console.log("the value has been set, do more stuff");
} else {
  console.log("the value was not set, handle the exception path");
}


Solution

  • This:

    if (myVar) {}
    

    will return false on all falsy values, like empty string (""), zero (0), false, null, and of course, undefined.

    If you do not expect any of the above values to pass through your if statement, then yes, it is logically equivalent.

    But, I would say that this is a bold statement that none of your if statements will contain 0 or "". These are common values.

    If you want to cleanup this code and continue to only check for undefined, then you can skip the typecheck and just check with:

    if (myVar === undefined) {}