Sunday, May 27, 2012

JavaScript === vs == : Does it matter which "equal' operator I use?

I'm using JSLint to go through some horrific JavaScript at work and it's returning a huge number of suggestions to replace == with === when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.

I'm basically wondering if there is a performance benefit to replacing == with === . Any performance improvement would probably be welcomed as there are hundreds (if not thousands) of these comparison operators being used throughout the file.

I tried searching for relevant information to this question, but trying to search for something like "=== vs ==" doesn't seem to work so well with search engines...

So... Would I be correct in assuming that if no type conversion takes place, there would be a small (probably extremely small) performance gain over == ?

Source: Tips4all


  1. The identity (===) operator behaves identically to the 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. It's this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same.

    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

    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.


    A good point was brought up by @Casebash in the comments and in @Phillipe Laybaert's answer concerning reference types. For reference types == 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 string literal with a string object created with 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.

  2. 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 compiler implicitly tries to convert the values and then does the comparing.

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

  3. In the answers here, I didn't read anything about what equal means. Some will say that === means equal and of the same type, but that's not really true. It actually means that both operands reference the same object, or in case of value types, have the same value.

    So, let's take the following code:

    var a = [1,2,3];
    var b = [1,2,3];
    var c = a;

    var ab_eq = (a === b); // false (even though a and b are the same type)
    var ac_eq = (a === c); // true

    The same here:

    var a = { x: 1, y: 2 };
    var b = { x: 1, y: 2 };
    var c = a;

    var ab_eq = (a === b); // false (even though a and b are the same type)
    var ac_eq = (a === c); // true

    Or even:

    var a = { };
    var b = { };
    var c = a;

    var ab_eq = (a === b); // false (even though a and b are the same type)
    var ac_eq = (a === c); // true

    This behavior is not always obvious. There's more to the story than being equal and being of the same type.

    The rule is:

    For value types (numbers):
    a === b returns true if a and b have the same value and are of the same type

    For reference types:
    a === b returns true if a and b reference the exact same object

    For strings:
    a === b returns true if a and b are both strings and contain the exact same characters

    Strings: the special case...

    Strings are not value types, but in Javascript they behave like value types, so they will be "equal" when the characters in the string are the same and when they are of the same length (as explained in the third rule)

    Now it becomes interesting:

    var a = "12" + "3";
    var b = "123";

    alert(a === b); // returns true, because strings behave like value types

    But how about this?:

    var a = new String("123");
    var b = "123";

    alert(a === b); // returns false !! (but they are equal and of the same type)

    I thought strings behave like value types? Well, it depends who you ask... In this case a and b are not the same type. a is of type Object, while b is of type string. Just remember that creating a string object using the String constructor creates something of type Object that behaves as a string most of the time.

  4. In PHP and JavaScript, it is a strict equality operator. Which means, it will compare both type and values.

  5. This question is more than a year old, but please let me add this counsel:

    If in doubt, read the specification!

    ECMA-262 is the specification for a scripting language of which Javascript is a dialect. Of course in the practice it matters more how the most important browsers behave than an esoteric definition how something is supposed to be handled. But it is helpful to understand why new String("a") !== "a".

    Please let me explain how to read the specification to clarify this question. I see that in this very old topic nobody had an answer for the very strange effect. So, if you can read a specification, this will help you in your profession tremendously. It is an acquired skill. So, let's continue.

    Searching the PDF file for === brings me to page 56 of the specification: 11.9.4. The Strict Equals Operator ( === ), and after wading through the specificationalese I find:

    11.9.6 The Strict Equality Comparison Algorithm
    The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
      1. If Type(x) is different from Type(y), return false.
      2. If Type(x) is Undefined, return true.
      3. If Type(x) is Null, return true.
      4. If Type(x) is not Number, go to step 11.
      5. If x is NaN, return false.
      6. If y is NaN, return false.
      7. If x is the same number value as y, return true.
      8. If x is +0 and y is −0, return true.
      9. If x is −0 and y is +0, return true.
      10. Return false.
      11. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
      12. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
      13. Return true if x and y refer to the same object or if they refer to objects joined to each other (see 13.1.2). Otherwise, return false.

    Interesting ist step 11. Yes, strings are treated as value types. But this does not explain why new String("a") !== "a". Do we have a browser not conforming to ECMA-262?

    Not so fast!

    Let's check the types of the operands. Try it out for yourself by wrapping them in typeof(). I find that new String("a") is an object, and step 1 is used: return false if the types are different.

    If you wonder why new String("a") does not return a string, how about some exercise reading a specification? Have fun!

  6. I tested this in Firefox with Firebug using code like this:

    var n = 0;
    while(true) {
    if(n==100000) break;


    var n = 0;
    while(true) {
    if(n===100000) break;

    My results (tested 5 times each and averaged):

    ==: 115.2
    ===: 114.4

    so I'd say that the miniscule difference (this is over 100000 iterations, remember) is negligible. Performance ISN'T a reason to do ===. Type safety (well as safe as you're gonna get in JS), and code quality is.

  7. In Javascript it means of the same value and type

    for example

    4 == "4" will return true


    4 === "4" will return false

  8. it checked for the same type also for both sides.

    var x = '1';
    var y = 1;
    x === y // false

    'string' != 'number' for example

  9. It's a strict check test.

    It's a good thing especially if you're checking between 0 and false and null.

    For example, if you have:

    $a = 0;



    All returns true and you may not want this. Let's suppose you have a function that can return the 0th index of an array or false on failure. If you check with "==" false, you can get a confusing result.

    So with the same thing as above, but a strict test:

    $a = 0;

    $a===0; // returns true
    $a===NULL; // returns false
    $a===false; // returns false

  10. It means equality without type coersion

    0==false // true
    0===false // false, different types

  11. The === operator is called a strict comparison operator, it does differ from the == operator.

    Lets take 2 vars a and b.

    For "a == b" to evaluate to true a and b need to be the same value.

    In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.

    Take the following example:

    var a = 1;
    var b = "1";

    if(a == b) //evaluates to true as a and b are both 1
    document.write("a == b");
    if(a === b) //evaluates to false as a is not the same type as b
    document.write("a === b");

    The === operator does not exist in strongly typed languages because it is not needed, but for weakly typed languages like Javascript it makes more sense.

    In summary: Using the == operator might evaluate to true in situations where you do not want it to, so using the === operator would be safer. In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.

  12. There is unlikely to be any performance difference between the two operations in your usage. There is no type-conversion to be done because both parameters are already the same type. Both operations will have a type comparison followed by a value comparison.

  13. From the core javascript reference
    === Returns true if the operands are strictly equal (see above) with no type conversion.

  14. In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1KB heavier than thousand "==" :) Javascript profilers can tell you if there is performance difference in your case.

    But personally i would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('\t\r\n' == 0) is true.

  15. it checks the values well as type of the variable to for equality

  16. I cover the differences in a post on my blog recently -

    Short story, == is equality comparision without type checking and === is equality comparision with type checking

  17. The problem is that you might easily get into trouble since JS have a lot of implicit conversions meaning ...

    var x = 0;
    var isTrue = x == null;
    var isFalse = x === null;

    Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...

    CString x;
    delete x;

    Which obviously during runtime does very undefined things...

    Google for impliciti conversions in C++ and STL to get some of the arguments against it...

  18. Here's a chart of how some "falsy" values compare.

  19. This link explains it:

  20. The equal comparison operator == is confusing and should be avoided. If you have to live with it, then remember the following 3 things:

    It is not transitive: (a == b) and (b == c) does not lead to (a == c)
    It's mutually exclusive to its negation: (a == b) and (a != b) always hold opposite Boolean values, with all a and b.
    In case of doubt, learn by heart the following truth table:


    The following set of 3 values are mutually equal, meaning that any 2 values among them are equal using the equal == sign

    Strange: note that any two values on the first column are not equal in that sense.

    '' == 0 == false // Any two values among these 3 ones are equal with the == operator
    '0' == 0 == false // Also a set of 3 equal values, note that only 0 and false are repeated
    '\t' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    '\r' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    '\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    '\t\r\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

    null == undefined // These two "default" values are not-equal to any of the listed values above
    NaN // NaN is not equal to any thing, even to itself.