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!

About the author

Jesse Skinner Hi, I'm Jesse Skinner. I'm a self-employed web developer with over two decades of experience. I love learning new things, finding ways to improve, and sharing what I've learned with others. I love to hear from my readers, so please get in touch!