-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.

11
  • 3
    There is nothing wrong with value == null Commented Feb 5, 2021 at 3:11
  • 2
    Does it prevent this with eslint? The eqeqeq ESLint rule has the smart option for allowing exactly this type of usage: eslint.org/docs/rules/eqeqeq Commented Feb 5, 2021 at 3:16
  • 2
    There's also ((value ?? null) !== null) I guess? Commented Feb 5, 2021 at 3:22
  • 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. Commented Feb 5, 2021 at 4:52
  • 1
    @Bergi agreed! I don't intend to recommend it. Commented Feb 5, 2021 at 14:24

1 Answer 1

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)

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

2 Comments

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.
Yes, false shouldn't be included. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.