Wil Boayue

Software Engineer/Architect

WTF Javascript - Type Coercion

I recently came across the site wtfjs.com. It highlights some idiosyncrasies of the Javascript language. It’s worth a look, you’ll get a deeper understanding of the Javascript language.

This entry submitted by @diogobaeder held my attention. The solution was not immediately obvious to me so I did some digging. Once I found the correct type coercion rules the result were logical.

1
2
3
var foo = [0];
console.log(foo == foo);  // true
console.log(foo == !foo);  // true - ???

These examine this step by step.

1
foo == foo

The above was obvious. References to the same object evaluate to true.

1
foo == !foo

The expression above took a little longer to decipher.

First the precedence rules come into play.

1
2
![0];         // conversion to Boolean(), false
[0] == false; // true

If either operand is a number or a boolean, the operands are converted to numbers.

1
2
3
4
Number(false) == 0;
Number([0]) == 0;

0 == 0;

Comments