JavaScript Three Equals

Even though == is called the equality operator it is not an equivalence relation on the set of JavaScript objects. It fails to partition each object into exactly one disjoint subset. This is because in JavaScript the == operator lacks transitivity. Observe:

a = '';
b = 0;
c = '0';
 
a == b; // => true
b == c; // => true
a == c; // => false

The reason this is the case is that the == operator perform type coercion on the objects being operated on, usually converting them to strings. This can lead to subtle bugs in code, and JavaScript doesn’t always make the source of errors obvious. Tools like JSLint issue a warning if you use == to compare values with 0 or null because a lot of strange things may pass that comparison.

A good rule of thumb is to always use === when doing comparisons, especially when 0 or null is involved. It will save you lots of headaches.

3 == '3' // => true
 
// And to play us out...
false == [[[[[[[[[[['']]]]]]]]]]] // => true

Leave a Reply

Your email address will not be published. Required fields are marked *