0

If you need to check whether a value is set i.e. not undefined or null, what would be the most convenient way to do it that does not sacrifice readability?

Here are some of the options I have been using:

  1. Clear and exact but long: if (value !== null && value !== undefined) {...}

  2. Short, exact but not clear if (value != null) {...}

  3. Short, not exact and not clear if (!value) {...} // true with 0, NaN and empty string

lehoang
  • 3,577
  • 1
  • 15
  • 16
  • 1
    Does this answer your question? [How to check empty/undefined/null string in JavaScript?](https://stackoverflow.com/questions/154059/how-to-check-empty-undefined-null-string-in-javascript) – tim Dec 06 '19 at 22:07
  • just take the first. it checks both unwanted values. – Nina Scholz Dec 06 '19 at 22:08
  • @tim: Not really, that question is more about checking an empty string, in this case, I want to check if the value is `null` or `undefined`. But thanks anyway! – lehoang Dec 09 '19 at 20:59
  • @NinaScholz: Yes, the first one is correct (and so does the second one). I just wonder if there are better way in terms of readability to achieve the same result. – lehoang Dec 09 '19 at 21:00

1 Answers1

0

undefined is a data type for javascript so it is necessary to validate undefined as well as empty or null value like this:

if (!value && value !== undefined) {...}
Rene Arteaga
  • 334
  • 3
  • 6
  • Thanks, but this is not what I'm asking for. I want to find a way to check if a value is not `null` or `undefined`. The solution you proposed, while getting rid of `undefined`, doesn't filter `null` value. – lehoang Dec 09 '19 at 21:04