I know that below are the two ways in JavaScript to check whether a variable is not null
, but I’m confused which is the best practice to use.
Should I do:
if (myVar) {...}
or
if (myVar !== null) {...}
I know that below are the two ways in JavaScript to check whether a variable is not null
, but I’m confused which is the best practice to use.
Should I do:
if (myVar) {...}
or
if (myVar !== null) {...}
if
myVar
is null then if block not execute other-wise it will execute.if (myVar != null) {...}
Sometimes if it was not even defined is better to be prepared. For this I used typeof
if(myVar) { code }
will be NOT executed only whenmyVar
is equal to:false, 0, "", null, undefined, NaN
or you never defined variablemyVar
(then additionally code stop execution and throw exception).if(myVar !== null) {code}
will be NOT executed only whenmyVar
is equal tonull
or you never defined it (throws exception).Here you have all (src)
if
== (its negation !=)
=== (its negation !==)
Here is how you can test if a variable is not NULL:
if (myVar !== null) {...}
the block will be executed if myVar is not null.. it will be executed if myVar is undefined or false or
0
orNaN
or anything else..There is another possible scenario I have just come across.
I did an ajax call and got data back as null, in a string format. I had to check it like this:
So, null was a string which read "null" rather than really being null.
EDIT: It should be understood that I'm not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I'm not sure why... perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It's frustrating to see this down-voted by someone who understands that it's not quite right, and then up-voted by someone it actually helps.
They are not equivalent. The first will execute the block following the
if
statement ifmyVar
is truthy (i.e. evaluates totrue
in a conditional), while the second will execute the block ifmyVar
is any value other thannull
.The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):
null
undefined
0
""
(the empty string)false
NaN