How to check if a variable is not 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) {...}
回答1
They are not equivalent. The first will execute the block following the if
statement if myVar
is truthy (i.e. evaluates to true
in a conditional), while the second will execute the block if myVar
is any value other than null
.
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
回答2
- code inside your
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). - code inside your
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)