Search code examples
javascriptequalityweak-typingidentity-operator

When would JavaScript == make more sense than ===?


As Which equals operator (== vs ===) should be used in JavaScript comparisons? indicates they are basically identical except '===' also ensures type equality and hence '==' might perform type conversion. In Douglas Crockford's JavaScript: The Good Parts, it is advised to always avoid '=='. However, I'm wondering what the original thought of designing two set of equality operators was.

Have you seen any situation that using '==' actually is more suitable than using '==='?


Solution

  • Consider a situation when you compare numbers or strings:

    if (4 === 4)
    {
      // true
    }
    

    but

    if (4 == "4")
    {
      // true
    }
    

    and

    if (4 === "4")
    {
      // false
    }
    

    This applies to objects as well as arrays.

    So in above cases, you have to make sensible choice whether to use == or ===