Confusing JavaScript Equality
I got tripped up today by something that took me a few minutes to figure out. I wrote this:
if (a == b == 0) { // only execute if both a and b are zero }
But this was wrong. In fact, you can write this:
alert(3 == 4 == 0); // alerts "true"
Why is that? Because of the order things are evaluated. I made the mistake of thinking == has the same result as doing =:
var x, y; x = y = 10; alert(x); // 10 alert(y); // 10
But when you use == like that, it actually compares the firsts two values, then compares the result (true or false) against the 3rd value. It's the same as writing:
alert(3 == 4 == 0); // true alert((3 == 4) == 0); // true
because 3 == 4 is false, and false == 0 is true!
Published on July 25th, 2007. © Jesse Skinner