Sunday, February 27, 2011

Equality, transitivity and JavaScript

One of the simplest ways to explain transitivity is using the equality operation, by saying that if A equals B and B equals C then A equals C. This is commonsense stuff, how can it be different.

Well, it can.

In JavaScript, the '==' (double equal) does type coercion, and therefore ends up in non-common-sense situation where equality in not transitive. See in the following example where  A equals B, B equals C, but still, A does NOT equals C :

'0' == 0 // true - the string 0 (zero) equals the number 0
0 == '' // true - the number zero equals empty string
'0' == '' // false - the string 0 (zero) does not equal empty string

seems that common sense is over appreciated...