-3
if(typeof(variable) === "boolean"){
  // variable is a boolean
}

Which one of the two code samples below is equivalent to the one above ?

Sample 1

if(variable === true || variable === false){
  // variable is a boolean
}

Sample 2

if(variable == true || variable == false){
  // variable is a boolean
}
meucaa
  • 1,455
  • 2
  • 13
  • 27
  • 1
    Clearly not the second, because `1 == true`, but is not a boolean – Eric Mar 15 '17 at 10:53
  • 1
    If that was your question, why not just try `typeof(1) == 'boolean'` in the console, rather than asking a human? – Eric Mar 15 '17 at 10:59

1 Answers1

2

The first case is equivalent. The === performs the same operation as the ==, except that it does not perform any type conversions. See this answer for more details.

So,

if ( variable === true || variable === false) {
    ...
}

Will evaluate to true only when variable is a boolean variable.


As for the inner workings of typeof, you can read this and, of course, it's manual. Keep in mind that typeof is a language operator, much like ===, ==, or &. To know exactly how it is implemented and how it knows the variable types, you need to check the code for it.

I never looked at a JavaScript Engine source code, so I don't know where you could look.

Community
  • 1
  • 1
Enzo Ferber
  • 3,029
  • 1
  • 14
  • 24