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

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: