Bitwise operations aren’t very common in JavaScript, but sometimes they’re indispensable.

To understand how bitwise operations work in JavaScript, you need to first understand what a binary system is and how to convert numbers from decimal to binary and back again.

An introduction to the binary number system can be found here.

Examples and Usage

Bitwise operators in JavaScript are quite hard to understand if you apply them to decimal numbers.

I suggest starting with a piece of paper and a pencil and writing down all the numbers in binary.

The AND, OR, XOR Operators

The operators &| and ^ require two numbers to function properly. They compare the bits in these numbers one-by-one, applying the rules from the table above.

Let’s try them out. The binary representation of a decimal number is in the comment.

const x = 5;   // 0101
const y = 6;   // 0110

It’s easier if you write the binary numbers one under the other like this:

AND 0101     OR 0101     XOR 0101
    0110        0110         0110
    ----        ----         ----
    0100        0111         0011

Now, we can add console.log and see if our calculations were right:

console.log(x & y);  // 4
console.log(x || y); // 7
console.log(x ^ y);  // 3

An important trick with XOR is that if you place the same number on both sides of it, you’ll always get zero.

console.log(x ^ x);  // 0
console.log(y ^ y);  // 0

On the contrary, if you replace ^ with either & or | the number won’t change.

#javascript #web dev #bitwise

How to Do Bit Manipulation in JavaScript
1.40 GEEK