0

In JavaScript I have a variable initialized with undefined. Now I'd like to check if it is either true or false.

Is there a statement more elegant than the following?

if (isValid === true || isValid === false) {
  // do something
}
Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

1 Answers1

2

How about checking if it is not undefined?

  • If it is neither true, nor false it has to be undefined.
  • So if it is not undefined, it is set and therefore either true or false.
if (isValid !== undefined) {
   // do something
}
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
  • Technically, the variable can now contain a number or a string now. However, if that's not expected, it should be fine to just check for NOT `undefined` instead of `true` or `false`, if those are the only three expected options. – VLAZ Aug 19 '19 at 10:53