-1

Is there a shorter way to checking if a value in JavaScript is null or undefined than this using new ES10 features like Nullish Coalescing?

(value !== null && value !== undefined)

There were other questions like

  1. Detecting an undefined object property in JavaScript
  2. How to determine if variable is 'undefined' or 'null'
  3. Is there a standard function to check for null, undefined, or blank variables in JavaScript?

But they all use either loose equality (==), use jQuery or return false even if the value is "", [] or 0.

Pushkin
  • 3,336
  • 1
  • 17
  • 30
  • 3
    There is nothing wrong with `value == null` – loganfsmyth Feb 05 '21 at 03:11
  • My project doesn't allow `==` – Pushkin Feb 05 '21 at 03:14
  • 2
    Does it prevent this with `eslint`? The `eqeqeq` ESLint rule has the `smart` option for allowing exactly this type of usage: https://eslint.org/docs/rules/eqeqeq – loganfsmyth Feb 05 '21 at 03:16
  • Yep, it worked, `eslint` didn't throw error for `value == null`, Thanks. – Pushkin Feb 05 '21 at 03:20
  • 2
    There's also `((value ?? null) !== null)` I guess? – jcalz Feb 05 '21 at 03:22
  • `((value ?? null) !== null)` is a good solution for `null` but does not work with `undefined` – DDomen Feb 05 '21 at 03:34
  • @DDomen but `undefined ?? null` produces `null`, and thus `(undefined ?? null) !== null` is false... have you tested it? – jcalz Feb 05 '21 at 03:38
  • @jcalz after answering my own question I saw your comment, so deleted it. But undeleted it and added more information and my testing as a snippet. But Thanks anyway. – Pushkin Feb 05 '21 at 03:43
  • @jcalz sorry I was misleaded by `!==` and `===`, I've tested for the equality instead of inequality. It does work. – DDomen Feb 05 '21 at 03:45
  • 1
    @jcalz `(value ?? null) !== null` might work but is totally weird. I would not recommend to write code like that, it's just a source of confusion. `value == null` is short, precise, well-known and idiomatic. Nothing about that changed with ES2020. – Bergi Feb 05 '21 at 04:52
  • 1
    @Bergi agreed! I don't intend to recommend it. – jcalz Feb 05 '21 at 14:24

1 Answers1

2

eslint will not throw an error for value == null if smart option is enabled

For project that doesn't have smart eqeqeq rule in eslint config,

There's a shorter way of doing it with Nullish Coalescing.

(value ?? null) !== null

let value

// undefined
console.log((value ?? null) !== null)

// null
value = null
console.log((value ?? null) !== null)

// ''
value = ''
console.log((value ?? null) !== null)

// 0
value = 0
console.log((value ?? null) !== null)

// []
value = []
console.log((value ?? null) !== null)
Pushkin
  • 3,336
  • 1
  • 17
  • 30
  • No, `(value ?? false) !== false` fails when `value === false`. If the question were "can we check if a value is `null`, `undefined`, or `false`?" then sure. – jcalz Feb 05 '21 at 03:36
  • Yes, `false` shouldn't be included. Thanks – Pushkin Feb 05 '21 at 03:39