Coding with Jesse

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

About the author

Jesse Skinner

I'm Jesse Skinner. I'm a self-employed web developer. I love writing code, and writing about writing code. Sometimes I make videos too. Feel free to email me if you have any questions or comments, or just want to share your story or something you're excited about.