this will do the trick for you
if (!!val) {
alert("this is not null")
} else {
alert("this is null")
}
this will do the trick for you
if (!!val) {
alert("this is not null")
} else {
alert("this is null")
}
There are 3 ways to check for "not null". My recommendation is to use the Strict Not Version.
1. Strict Not Version
if (val !== null) { ... }
The Strict Not Version uses the Strict Equality Comparison Algorithm. The !== operator has faster performance than the != operator, because the Strict Equality Comparison Algorithm doesn't typecast values.
2. Non-strict Not Version
if (val != null) { ... }
The Non-strict Not Version uses the Abstract Equality Comparison Algorithm. The != operator has slower performance than the !== operator, because the Abstract Equality Comparison Algorithm typecasts values.
3. Double Not Version
if (!!val) { ... }
The Double Not Version has faster performance than both the Strict Not Version and the Non-Strict Not Version. However, the !! operator will typecast "falsey" values like 0, '', undefined and NaN into false, which may lead to unexpected results, and it has worse readability because null isn't explicitly stated.
Good way to check for variable being not null and not undefined.
Could someone explain why "" != null? - JavaScript - SitePoint Forums | Web Development & Design Community
What’s the best way to use JavaScript if not null to check if a variable is not null? - LambdaTest Community
What is the best method to check if a variable is not null or empty?
Videos
Hi, all, I often do stuff like this in my code, to check for a variable being not null and not undefined.
// check if value is not null and not undefined
if (value) {
...
}However, I'm now thinking this can leads to bugs, because of 0, "", false and NaN also being falsy.
What is a better way to check a variable is not null and not undefined? I could use this I think, wondering if there is something shorter than this:
if (typeof value !== 'undefined' || value !== null) {
...
}