• Confusing JavaScript Equality

    Jul 25 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 at 5:35pm on July 25, 2007

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

    2. Mark at 2:15pm on August 8, 2007

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

    Commenting is now closed. Come find me on Twitter.