2

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)
FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225
  • 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. – Sebastian Simon Jan 01 '23 at 12:58
  • There's a long discussion with multiple approaches https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in – Wiktor Zychla Jan 01 '23 at 12:59

1 Answers1

6

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.

rocambille
  • 15,398
  • 12
  • 50
  • 68
  • While indeed `undefined == null` is true `undefined !== null` is true as well. – 丶 Limeー来夢 丶 Jul 29 '23 at 02:32
  • 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. – Ivan P Aug 11 '23 at 18:26
  • @丶Limeー来夢丶 `!==` is the negated version of `===`, `undefined != null` is false as one would expect – umnikos Aug 29 '23 at 12:21