Coding with Jesse

Confusing JavaScript Equality

July 25th, 2007

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!


Comments

1 . Arjan Eising on July 25th, 2007

Arjan Eising

Such things can really give you a headache when you can't find the problem...

2 . Mark on August 8th, 2007

Mark

OMG, it even took me a few moments to get the line:
"because 3 == 4 is false, and false == 0 is true!"
LOL

Comments are closed, but I'd still love to hear your thoughts.