10

Is it possible to check for nullish values as part of an if block, without resorting to a pair of explicit checks for null and undefined.

For example, don't want to do this:

if(key === null || key === undefined) {
    // do something
}

This doesn't work, because it also includes other falsy values such as zero and empty array.

if(!key)
2
  • 1
    An empty array is not falsy. There’s the ?? (nullish-coalescing) operator and there’s the == operator. There’s also Object.hasOwn. What is done with key? The best alternative depends on more context. Commented Jan 1, 2023 at 12:58
  • There's a long discussion with multiple approaches stackoverflow.com/questions/5515310/… Commented Jan 1, 2023 at 12:59

1 Answer 1

17

That's one of the good use cases of the operator ==:

if(key == null) {
    // do something
}

This will work with both null and undefined, while keeping away other falsy values.

Sign up to request clarification or add additional context in comments.

4 Comments

While indeed undefined == null is true undefined !== null is true as well.
While this is clearly a working answer in any codebase maintained by more than one person I would strongly question the readability of this code. The maxim that code is read more than written is true. JS has a bunch of quirks and I'd just avoid falling back on them altogether.
@丶Limeー来夢丶 !== is the negated version of ===, undefined != null is false as one would expect
Using if( Boolean(key) ) would be better as it also checks if any value including 0 (zero) is falsy/nullish

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.