Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 500
Afshin Mehrabani Avatar asked Feb 14 '13 08:02

Afshin Mehrabani


People also ask

What is difference between bitwise operator and logical operator?

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.

Is logical AND bitwise the same?

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.

Why do we use logical operators?

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.

Can I use bitwise instead of logical?

The answer is yes, you can.


1 Answers

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!

like image 63
Christoph Avatar answered Oct 18 '22 13:10

Christoph