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 d
if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, ""empty string, false, NaN
never use number type like id as
if (id) {}
for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.
So for id type, we must use following:
if ((Id !== undefined) && (Id !== null) && (Id !== "")){
} else {
}
for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.
if (string_type_variable) { }
if myVar
is null then if block not execute other-wise it will execute.
if (myVar != null) {...}
if(myVar) { code }
will be NOT executed only when myVar
is equal to: false, 0, "", null, undefined, NaN
or you never defined variable myVar
(then additionally code stop execution and throw exception).if(myVar !== null) {code}
will be NOT executed only when myVar
is equal to null
or you never defined it (throws exception).Here you have all (src)
if
== (its negation !=)
=== (its negation !==)