1

Is there a shorter, cleaner way to match explicit true or false values only in JS? No match for undefined or anything else.

 if (var1 == true|| var1==false){}
Nabil A
  • 71
  • 3
  • 1
    There is, and it's worth reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness because the concepts of equality and identity are fundamental to JS, and important to know if you don't want your code to surprise you by doing exactly what it's supposed to. – Mike 'Pomax' Kamermans Sep 27 '20 at 23:15

1 Answers1

6

Use typeof instead:

if (typeof var1 === 'boolean') {
}

Note that you should not use sloppy comparison with == - always use === (and cast types explicitly if needed) if you want to avoid weird auto-coercion bugs.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320