Mark Taylor
Mark Taylor

Reputation: 1188

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");
}

Upvotes: 0

Views: 124

Answers (4)

sonEtLumiere
sonEtLumiere

Reputation: 4562

With exclamation sign you can check that variable to the opossite boolean value, for example undefined, false, an empty string, null and 0 are falsy values

let myVar = undefined;
if(!myVar){
    console.log('type of: ' + typeof(myVar))
}   

myVar = '';
if(!myVar){
    console.log('type of: ' + typeof(myVar))
}   

myVar = false;
if(!myVar){
    console.log('type of: ' + typeof(myVar))
}   

Upvotes: 0

MattDiamant
MattDiamant

Reputation: 8771

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) {}

Upvotes: 2

Randy Casburn
Randy Casburn

Reputation: 14165

They can look that way, but might not turn out as your expect.

Here some further proof:

const tests = [false, undefined, null, '', NaN, 0, -0, 0n, 'anything else'];
tests.map(t=> console.log(t ? t + ' is truthy' : t + ' is falsy'));

Upvotes: 1

Phúc Nguyễn
Phúc Nguyễn

Reputation: 11

No. Because in this case if(myVar) if myVar = 0, false, "",undefined will be return false. And if (typeof(myVar) != "undefined") just return false when myVar = undefined

Upvotes: 0

Related Questions