Application of bitwise operators in JavaScript

First of all let us revise what bitwise operators are and why you should comprehend them in 2017. Bitwise operators are operators that work on a bit or two bits (comparing them and giving a result based on the comparison) at a time.

AND ( & ) will  be 1 only if both of the bits are 1, otherwise it will be 0.
Example (all combinations): 1&1=1;  1&0=0;  0&1=0;  0&0=0;

OR ( | ) will be 1 if there is a 1 present when comparing two bits,
Example (all combinations): 1|1=1;  1|0=1;  0|1=1;  0|0=0;

XOR ( ^ ) is 1 only if one bit is 1 and the other is 0 no matter the order (1 XOR 0 =1)
(0 XOR 1=1)

NOT ( ~ ) if the bit is 0 it will go to 1 if it is 1 it will go to 0. In this case there is no comparison with other data. If you have an integer, let’s say 5 which is 0101 then the NOT will bring it to 1010.

To see the truth tables go to this website
Practical applications of bitwise operators (real life):
0X1 represents 1 in hexadecimal.


  • We check if the value is odd. If it is, the program returns true it’s not (if it is even) then the program returns false:


(value & 0x1) > 0

Explanation: Let’s say we have a value of 8 and on the other side we have 0x1. We convert them to binary numbers (that’s what the computer only understands at the most bottom level). We write the numbers one below the other and start the calculation from the most right bit to the most left bit (refer to the and operator above)

1000
0001


0000

The result is 0000 which is 0 in denary (decimal ). Zero is not greater than zero so the expression returns false. Which means that the number is even.

JS code:

console.log((8 & 0x1) > 0)
  • Use them for data encryption (encryption is all about bitwise operators)

a = 1903349;
b = 4542345;
c = 5834533;
hash = a ^ b ^ c;

The numbers will be converted to binary and will be hashed (they will be transformed in some boolean XOR equivalent data)

Conclusion:

Bitwise operators are rarely used in JavaScript (as far as I’ve seen in 5 years of coding). I suppose interviewers use them for questions for future employees to see how deep the candidate went with their programming knowledge. Still, it is good to know them because once you see them and maybe have to do something with them you will have the basic knowledge in your head and solving the problem in front of you will require less time and frustration.

So, when doing operation with bitwise operators which are nothing else but boolean operations, always have in mind the truth tables which are easy to understand and learn.

My opinion is, try to avoid them because your code looks incomprehensible to others who may in the future maintain your application. The more clearer you are the better for everyone else.