Demystifying Bitwise Operators in JavaScript
Tags: javascript, tutorial, learning
Published: 2023-07-24 07:59:01

Welcome to the world of JavaScript's hidden gems: bitwise operators. These powerful tools enable binary manipulation, offering developers the ability to achieve impressive feats with seemingly complex tasks.

In this blog, we'll demystify bitwise operators in JavaScript, exploring their fundamental concepts. By the end, you'll be equipped to leverage these operators to optimize performance, tackle intricate algorithms, and unlock new possibilities in your projects. Let's dive in!

In JavaScript, bitwise operators provide the means to manipulate individual bits of binary numbers, offering unique capabilities beyond traditional arithmetic and logical operations. Instead of treating numbers as whole entities, bitwise operators allow you to work with their binary representations, enabling a more granular level of control over data.

### How They Are Helpful:

1. Efficient Data Storage: Bitwise operators can be valuable in scenarios where data needs to be stored efficiently. By representing multiple Boolean values as individual bits within a single integer, you can reduce memory usage and optimize data structures.

2. Flags and Options: When dealing with configuration options or flags, bitwise operators shine. They allow you to set, unset, or check specific bits, enabling a compact representation of multiple options or states within a single variable.

3. Low-Level Operations: In certain cases, you might need to perform low-level operations, such as accessing and manipulating hardware or handling binary protocols. Bitwise operators offer the necessary tools for these tasks.

4. Masking and Bit Extraction: Using bitwise AND and OR operations, you can create masks to extract specific bits or control which bits in a number should be modified.

5. Arithmetic Optimization: Bitwise operators are sometimes used to perform certain arithmetic operations more efficiently, especially when working with negative numbers and two's complement representation.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xs4r2kxzekxai1o9y27h.jpg)

### Binary Number System

Now, you might be wondering, what are bits and binary numbers? Let me explain.

In everyday life, we use a base-10 number system (decimal system) with digits ranging from 0 to 9. However, computers use a base-2 number system (binary system) with only two digits: 0 and 1. These 0s and 1s are called bits, and they are the building blocks of all information inside a computer.

To better understand this, let's consider a simple example using decimal and binary numbers:

Decimal: 5
Binary: 101

Here, the decimal number 5 is represented as 101 in binary. Each digit (0 or 1) in the binary number is a bit, and the rightmost bit represents the 1's place, the next bit to the left represents the 2's place, then 4's place, and so on.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ip37aujy017gubthrbkh.jpg)

### The Bitwise AND (&) operator

Imagine you have two binary numbers, which are sequences of 0s and 1s. In this case, let's take the binary representations of two decimal numbers: 5 and 3.

* The binary representation of 5 is 101.
* The binary representation of 3 is 011.

Now, let's use the "Bitwise AND (&) operator" on these binary numbers. The operator works by comparing each pair of corresponding bits in the two numbers and produces a new binary number as a result.

To do this, line up the binary digits of both numbers, and for each position, apply the following rules:

* If both bits are 1, write 1 in the result.
* Otherwise, write 0 in the result. 

The syntax for the Bitwise AND operator is:
`expression1 & expression2`

Here's how the bitwise AND works for 5 and 3:
```
var numOne = 5;  // binary representation: 101
var numTwo = 3;  // binary representation: 011

var result = numOne & numTwo
console.log(result) // Output: 1
```

In this example, the bitwise AND operator takes the binary representations of 5 and 3, compares each corresponding pair of bits, and gives us the result 001, which is 1 in decimal notation.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kipi42c7fr336n1cpgmq.jpg)

### The Bitwise OR (|) operator

Just like before, we'll use binary numbers to explain this concept. Binary numbers consist of 0s and 1s, and the Bitwise OR operator (|) compares corresponding bits of two numbers and produces a new binary number as a result.

Now, we'll use the "Bitwise OR (|) operator" on these binary numbers. Line up the binary digits of both numbers, and for each position, apply the following rules:

* If at least one of the bits is 1, write 1 in the result.
* Otherwise, write 0 in the result. 

The syntax for the Bitwise OR operator is:
`expression1 | expression2`

Here's how the bitwise OR works for 5 and 3:
```
var numOne = 5;  // binary representation: 101
var numTwo = 3;  // binary representation: 011

var result = numOne | numTwo;
console.log(result);  // Output: 7
```

The bitwise OR operator compares each corresponding pair of bits from the binary representations of 5 and 3, and it gives us the result 111, which is 7 in decimal notation.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n6q6g4jwck51uxt3szju.jpg)

### The Bitwise XOR (^) operator

Bitwise XOR (^) operator compares corresponding bits of two numbers and produces a new binary number as a result.

Now, let's use the "Bitwise XOR (^) operator" on these binary numbers. Line up the binary digits of both numbers, and for each position, apply the following rules:

* If the bits are different (one is 0 and the other is 1), write 1 in the result.
* If the bits are the same (both 0s or both 1s), write 0 in the result. 

The syntax for the Bitwise XOR operator is:
`expression1 ^ expression2`

Here's how the bitwise XOR works for 5 and 3:
```
var numOne = 5;  // binary representation: 101
var numTwo = 3;  // binary representation: 011

var result = numOne ^ numTwo;
console.log(result);  // Output: 6
```

The bitwise XOR operator compares each corresponding pair of bits from the binary representations of 5 and 3, and it gives us the result 110, which is 6 in decimal notation.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0khtxtmzpr481c47ggux.jpg)

### The Bitwise NOT (~) operator

The Bitwise NOT (~) operator is a unary operator, meaning it operates on a single value. Unlike the previous bitwise operators (AND, OR, and XOR), the Bitwise NOT operator only requires one operand. It takes a single number (integer) and performs the NOT operation on its binary representation.

To understand the Bitwise NOT operator, we need to grasp the concept of Two's complement. In Two's complement representation:

1. Positive integers are represented as usual in binary form.
2. To represent a negative integer, we first represent its positive counterpart in binary and then invert all the bits (0s become 1s and 1s become 0s) and add 1 to the result.

The syntax for the Bitwise NOT operator is:
`~expression`

Now, let's see how the Bitwise NOT operator works on a positive integer:

Suppose we have the decimal number 5, which is represented in binary as 101.

The Bitwise NOT operator (~) will invert all the bits of 101, resulting in:
```
var number = 5;  // binary representation: 101

var result = ~number;
console.log(result);  // Output: -6
```

As you can see, the result of the Bitwise NOT operator on 5 is -6 in decimal notation. This is because, in Two's complement representation, the binary number 010 represents the negative integer -6.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ia7pbtfsc05fv5ljzb87.jpg)

### Conclusion

In this article, we've explored JavaScript's bitwise operators, which offer powerful ways to manipulate individual bits of integers. The Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^), and Bitwise NOT (~) operators each serve unique purposes, from checking and setting bits to toggling and complementing values. By mastering these operators, you can enhance code efficiency and unlock new possibilities in JavaScript programming.

Connect with me!
[LinkedIn](https://www.linkedin.com/in/hrshainik) | [Instagram](https://www.instagram.com/traveloperhabib) | [Twitter](https://twitter.com/traveloperhabib) | [GitHub](https://github.com/hrshainik)

I'm excited to connect with fellow developers, tech enthusiasts, and industry professionals. Feel free to reach out, connect, and let's create meaningful interactions in the world of technology!