What’s the reason to use === instead of == with typeof in Javascript?

To answer the main question – there is no danger in using typeof with ==. Below is the reason why you may want to use === anyway.


The recommendation from Crockford is that it’s safer to use === in many circumstances, and that if you’re going to use it in some circumstances it’s better to be consistent and use it for everything.

The thinking is that you can either think about whether to use == or === every time you check for equality, or you can just get into the habit of always writing ===.

There’s hardly ever a reason for using == over === – if you’re comparing to true or false and you want coercion (for example you want 0 or '' to evaluate to false) then just use if(! empty_str) rather than if(empty_str == false).


To those who don’t understand the problems of == outside of the context of typeof, see this, from The Good Parts:

'' == '0'          // false
0 == ''            // true
0 == '0'           // true

false == 'false'   // false
false == '0'       // true

false == undefined // false
false == null      // false
null == undefined  // true

' \t\r\n ' == 0    // true

Leave a Comment