Explicit Equivalence

Here is the second in the series on 5 Things Everyone Could Learn From the jQuery Source:

2) Explicit Equivalence

Sometimes, it’s not enough to verify that two things are ‘mostly’ the same. We want to make sure that they are completely and totally the same. JavaScript (as well as several other programming languages) give you the ability to determine if two things are explicitly equal by changing the operator we use to test. You will see the following example code (This example decidedly NOT in jQuery source) very frequently:

if (x == 2) {

If we are reading this in plain English, we would say ‘If the value of x is equal to 2, do some cool stuff’ and that would be just fine. We know that if we just said:

if (x = 2) {

…that it would always work. We can always assign a value to a variable, and that is what the single equals(=) does, it assigns. Two equals compare the values. However, we can go a step further. We can use three equals signs to test the explicit equivalence, and by explicit equivalence I mean that not only do the two things being compared have the same value, but the same type as well.

If we do this:

var x = 2, y = "2";

And then we do this:

if (x==y)

This will evaluate to true. The reason for this is that JavaScript engines (like V8 in Chrome) look at these two and nicely cast these two values to the same type so that they can be compared properly. So the integer 2 and the string “2″ will become the same type and can be determined to be ‘equal’.

However, if we do the same variable assignments and then do:

if (x===y)

This comparison will be false. The reason is that while both have the same ‘value’, they are not the same type. One is an integer, the other is a string. This is called explicit equivalence, and it is very powerful.

* – DISCLAIMER: There are 38 uses of == in the jQuery source compared to 380 instances of ===. And the decision of which to use is worth discussing here. The case where you always want to (and truthfully have to) use == instead of === is when you are testing if something is null. This is important to note because null does not have a type. It is neither an integer, string, object, array, or any other type of thing. It’s nothing. It’s null. It is the absence of all that is good and bright in the world. Therefore, you cannot check value AND type on null.

#1 in the series can be found here.

Published 5 Feb 2011

Writing better code by building better JavaScript
Don Burks on Twitter