Search code examples
javascriptoperatorsbitwise-operatorslogical-operators

Why use logical operators when bitwise operators do the same?


Consider this condition:

(true & true & false & false & true) == true //returns: false

As you can see, the bitwise AND behavior is exactly like logical AND's:

(true && true && false && false && true) == true //returns: false

I'm wondering why I should use logical operations when the bitwise operations do the same as the logical ones.

Note: Please don't answer that's because of performance issue because it's pretty much faster in Mozilla Firefox, see this jsPerf: http://jsperf.com/bitwise-logical-and


Solution

  • The most common use of short-circuit evaluations using logical operators isn't performance but avoiding errors. See this :

    if (a && a.length)
    

    You can't simply use & here.

    Note that using & instead of && can't be done when you don't deal with booleans. For example & on 2 (01 in binary) and 4 (10 in binary) is 0.

    Note also that, apart in if tests, && (just like ||) is also used because it returns one of the operands :

    "a" & "b" => 0
    "a" && "b" => "b"
    

    More generally, using & in place of && is often possible. Just like omitting most ; in your javascript code. But it will force you to think more than necessary (or will bring you weird bugs from time to time).