this will do the trick for you
if (!!val) {
alert("this is not null")
} else {
alert("this is null")
}
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) {
...
}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.
JavaScript “null is not an object”
Guessing some amount of time and using a setTimeout is a bad strategy, because the amount of time it'll take for the page to get loaded and parsed can vary. If you're correct that the problem is the elements not being parsed at the point you're trying to select them, you need to wrap all your function calls in an event listener for either the DOMContentLoaded event or the load event. These enable you to reliably execute your code only once the page has finished parsing.
More on reddit.com