Why use logical operators when bitwise operators do the same?
bitwise operations behavior the same?
No, it's not. Bitwise operators work on integer numbers, while the logical operators have stronlgy different semantics. Only when using pure booleans, the result may be similar.
- Bitwise operators: Evalutate both operands, convert to 32-bit integer, operate on them, and return the number.
- Logical operators: Evaluate the first operand, if it is truthy/falsy then evalutate and return second operand else return the first result. This is called Short-circuit evaluation
You already can see this difference in the type of the result:
(true & true & false & false & true) === 0
(true && true && false && false && true) === false
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).