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

后端 未结 5 1892
执笔经年
执笔经年 2020-11-29 09:23

Throughout many third-party libraries and best practices blogs/recommendations, etc... it is common to see syntax like this:

typeof x === \'object\' (instead         


        
5条回答
  •  忘掉有多难
    2020-11-29 09:56

    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
    

提交回复
热议问题