Why use === instead of == when comparing a String

This question already has an answer here:

  • Which equals operator (== vs ===) should be used in JavaScript comparisons? 50 answers

  • The === operator ensures that not only the values are equal, but the two items being compared are of the same type too; Whereas the == operator only checks that the values of the two items are equal

    As @amnotiam mentioned in the comments, you may also want to check out the The Abstract Equality Comparison Algorithm


    === is used for checking value with type..

    var str="300";
    
    //this gt execute
    if(str==="300")
    {
            alert("this alert get executed");
    }
    
    
    //this not execute
    if(str===300)
    {
            alert("this alert not get executed");    
    }
    

    for == below both code is valid because its not check for type

    //this get execute
    if(str=="300")
    {
            alert("this alert get executed");
    }
    
    
    //this get execute
    if(str==300)
    {
            alert("this alert get executed");
    }
    

    10 == '10'  // true  | check value: 10 equal 10
    10 == 10    // true  | check value: 10 equal 10
    
    10 === '10' // false | check type: int not equal string
    10 === 10   // true  | check type: int equal int, check value: 10 equal 10
    

    检查类型与否。

    链接地址: http://www.djcxy.com/p/3260.html

    上一篇: 如何检查在JavaScript中的“未定义”?

    下一篇: 比较字符串时为什么使用===而不是==