Check for Not Null
TODO: collapasable, copyable, download, etc
What is the idiomatic javascript to check if a value is not null and not undefined. false, 0, '' should pass the testIn JavaScript, to check if a value is not null
and not undefined
(while allowing values like false
, 0
, and ''
to pass the test), you would typically use a strict inequality check against both null
and undefined
. However, since null
and undefined
are the only falsy values you want to exclude, you can use a comparison that leverages the fact that null
and undefined
are loosely equal to each other but not to any other falsy values. Here's how you do it:
if (value !== null && value !== undefined) {
// Your code here: this block runs if value is anything other than null or undefined.
}
Alternatively, a more concise way to perform the same check is to use the strict inequality operator (!==
) against undefined
while taking advantage of the fact that null
is loosely equal to undefined
. This approach works because the loose equality check (==
or !=
) treats null
and undefined
as equal, but strict equality (===
or !==
) does not:
if (value !== undefined && value !== null) {
// This block will execute if `value` is anything other than `null` or `undefined`.
}
But if you prefer a more concise approach, leveraging the fact that both null
and undefined
are the only values that are equal to undefined
under loose equality (==
), you can simply write:
if (value != null) {
// This block will execute if `value` is not `null` and not `undefined`.
}
This last example is idiomatic and takes advantage of JavaScript's type coercion rules to exclude both null
and undefined
in a single check, allowing all other values (including false
, 0
, and ''
) to pass the test.
Related Chats
JS Optional Chaining Operator 0.532
Nullish Coalescing Operator Summary 0.485
React JSX Conditional Rendering 0.400
TS Default Value Fix 0.378
JavaScript to TypeScript Transition 0.360
Modern ES6 Array Filtering 0.356
Tests Funktion sortByMessageId 0.348
Using Sets for Uniqueness 0.337
Find parent with class. 0.321