Categories
equality equality-operator identity-operator javascript operators

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

5653

I’m using JSLint to go through JavaScript, and it’s returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.

Is there a performance benefit to replacing == with ===?

Any performance improvement would be welcomed as many comparison operators exist.

If no type conversion takes place, would there be a performance gain over ==?

    7022

    The strict equality operator (===) behaves identically to the abstract equality operator (==) except no type conversion is done, and the types must be the same to be considered equal.

    Reference: Javascript Tutorial: Comparison Operators

    The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.

    To quote Douglas Crockford’s excellent JavaScript: The Good Parts,

    JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:

    '' == '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
    

    Equality Comparison Table

    The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.


    Update:

    A good point was brought up by @Casebash in the comments and in @Phillipe Laybaert’s answer concerning objects. For objects, == and === act consistently with one another (except in a special case).

    var a = [1,2,3];
    var b = [1,2,3];
    
    var c = { x: 1, y: 2 };
    var d = { x: 1, y: 2 };
    
    var e = "text";
    var f = "te" + "xt";
    
    a == b            // false
    a === b           // false
    
    c == d            // false
    c === d           // false
    
    e == f            // true
    e === f           // true
    

    The special case is when you compare a primitive with an object that evaluates to the same primitive, due to its toString or valueOf method. For example, consider the comparison of a string primitive with a string object created using the String constructor.

    "abc" == new String("abc")    // true
    "abc" === new String("abc")   // false
    

    Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they’re not the same type and returning false. Which one is correct? That really depends on what you’re trying to compare. My advice is to bypass the question entirely and just don’t use the String constructor to create string objects from string literals.

    Reference
    http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

    4

    • 9

      I’d also point out that 0 === -0 and NaN !== NaN, which can be confusing sometimes. If you want to differentiate ±0 and consider NaNs equal, use Object.is (ES2015)

      Oct 11, 2020 at 13:39

    • 8

      Soft typing is a feature. Obviously Crockford is pointing out some of the “artifacts” of the design decision, but soft typing is still a feature. If used correctly, it’s absolutely fine to use. Don’t throw the baby away with the bathwater.

      – aross

      Mar 25, 2021 at 9:29

    • Why would you ever need to use -0?

      Sep 15, 2021 at 2:06

    • 3

      @AdrianLarson It’s a quirk of IEEE-754 floating point. There’s no practical use for it, but because an IEEE-754 “double” is a “signed magnitude” format, negative zero “exists”. However, to avoid surprises, it’s defined to equal positive zero. JavaScript (well, ECMAScript) defines (-0).toString() as "0", but not every language does (eg. in C#, Math.Round(-0.1).ToString() is "-0"). That can lead to weird fixes like x == 0 ? 0 : x.

      Feb 27 at 15:56


    1225

    Using the == operator (Equality)

    true == 1; //true, because 'true' is converted to 1 and then compared
    "2" == 2;  //true, because "2" is converted to 2 and then compared
    

    Using the === operator (Identity)

    true === 1; //false
    "2" === 2;  //false
    

    This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing.

    On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing.

    1

    • 1

      I don’t think that identity is the correct term here/ === checks equality and type (called strict). Idendity usually refers to ‘sameness’, which is provisioned by the Object.is function (as per ES2015).

      – BanksySan

      Mar 24 at 10:53

    858

    Here’s an interesting visualisation of the equality comparison between == and ===.

    Source: https://github.com/dorey/JavaScript-Equality-Table (demo, unified demo)


    var1 === var2

    When using === for JavaScript equality testing, everything is as is.
    Nothing gets converted before being evaluated.

    Equality evaluation of === in JS

    var1 == var2

    When using == for JavaScript equality testing, some funky conversions take place.

    Equality evaluation of == in JS

    Summary of equality in Javascript

    Equality in Javascript


    Conclusion:

    Always use ===, unless you fully understand the funky conversions that take place with ==.

    8

    • 5

      A better ‘==’ table: algassert.com/visualization/2014/03/27/…

      May 24, 2021 at 14:40


    • At least == comparisons are commutative (i.e. (a==b) === (b==a)) XD

      – imkzh

      Nov 30, 2021 at 8:38

    • @imkzh Relations are more commonly called symmetric rather than commutative. But what I actually came here to say: == is not transitive! (even when ignoring NaN)

      Apr 20 at 15:13

    • @Feuermurmel: Can you give an example of when == is non-transitive?

      – SNag

      Apr 20 at 18:15

    • Oh, sorry for the late response. @SNag Definitely. Take a = [], b = false and c = [0].

      Apr 27 at 10:18