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

后端 未结 5 1877
执笔经年
执笔经年 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:37

    Triple equal operators are mostly used for variable type and value checking (all in 1 expression), also known as equality without type coercion.

    Example:

    var a = 1;
    var b = 1;
    var c = "1";
    var d = "1";
    
    alert (a === b); //True, same value and same type (numeric)
    alert(c === d); //True, same value and same type (string)
    alert(b === c); //False, different type but same value of 1
    

    See Doug Crockford's YUI Theater on type coercion.


    If the typeof operator already returns a string, what's the need to type check the return value as well? If typeof(typeof(x)) is always string, no matter what x actually is, then == should be sufficient and === unnecessary.

    The most efficient reason for not using typeof and rather the === operator would be for type coercion (interpretation) between browsers. Some browsers can pass 6=="6" as true and some wouldn't (depending on the strictness of the JS interpreter) so by introducing type coercion would clarify this. Also, it would bring the "Object-Orientativity" approach to it since JavasScript's variables are not type-based variables (i.e. variable types are not declared on compile time like in Java).

    E.g. in Java, this would fail:

    if ("6" instanceof Number) { // false
    

    Hope I answered your question.

提交回复
热议问题