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