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
Difference Between Bitwise and Logical Operators First, logical operators work on boolean expressions and return boolean values (either true or false), whereas bitwise operators work on binary digits of integer values (long, int, short, char, and byte) and return an integer.
The key difference between Bitwise and Logical operators is that Bitwise operators work on bits and perform bit by bit operations while logical operators are used to make a decision based on multiple conditions.
The logical operators are used primarily in the expression evaluation to make a decision. These operators allow the evaluation and manipulation of specific bits within the integer. This operator returns true if all relational statements combined with && are true, else it returns false.
The answer is yes, you can.
Almost everything is already said, but just for completeness' sake I want to take a look at the performance aspect (which you said doesn't matter, but it very well might):
JavaScript has a lot of difficult-to-remember rules on how to evaluate expressions. This includes a lot of type casting (implicit type coercion) when it comes to more complex comparisons. Arrays and Objects need to be converted by calling their toString()
methods and are then cast to numbers. This results in a huge performance hit.
The logical operator &&
is short-circuiting. This means as soon as it encounters a falsy value, the evaluation stops and false
is returned. The bitwise operator will always evaluate the entire statement.
Consider the following (yes, quite extreme) short circuit example when very expensive operations (casting an array and an object) are involved: ( performance according to https://jsbench.me in Chromium 90)
// logical operator
( false && {} && [] ) == true
// /\ short circuits here
// performance: 805M ops/sec
// bitwise operator
( false & {} & [] ) == true // evaluates the entire statement
// performance: 3.7M ops/sec
You can see that the performance differs by a factor of 100!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With