# Bitwise operator in JavaScript

What you will learn here about JavaScript

- Bitwise operator in JavaScript

Bitwise operators are used to perform operation on bits of data or value or number. JavaScript supports 7 bitwise operators and those are

- AND ( & )
- OR ( | )
- XOR ( ^ )
- NOT ( ~ )
- Left Shift ( << )
- Right Shift(Sign Propogation)( >> )
- Right Shift (Zero fill) ( >>> )

### 1)AND ( & )

Bitwise AND( & ) operator is to perform AND operation on bits of value or number. Bitwise AND operation return 1 only when both bits are 1.

Bitwise AND Truth table

0 & 0 = 0;

1 & 0 = 0;

0 & 1 = 0;

1 & 1 = 1;

How Bitwise AND works:

1)JavaScript convert first number to binary format

2)JavaScript convert second number to binary format

3)Perform Bitwise AND operation on respective bits

4)Returns decimal value of resultant binary

var a=5; //binary is 101

var b=3; //binary is 011

var result= a & b; //result is 1

### 2)OR ( | )

Bitwise OR operator is used to perform OR operation on bits of value or number. Bitwise OR operation return 1 when either of bit is 1.

Bitwise OR Truth table

0 | 0 = 0;

1 | 0 = 1;

0 | 1 = 1;

1 | 1 = 1;

Example of Bitwise OR

var a=5; //binary is 101

var b=3; //binary is 011

var result= a | b; //result is 7

### 3)XOR ( ^ )

Bitwise XOR is odd 1 detector. When both bits are same it return 0 else it returns 1.

Bitwise XOR Truth table

0 ^ 0 = 0;

1 ^ 0 = 1;

0 ^ 1 = 1;

1 ^ 1 = 0;

Example of Bitwise XOR

var a=5; //binary is 101

var b=3; //binary is 011

var result= a ^ b; //result is 6

### 4)NOT ( ~ )

Bitwise NOT first performs the 1’s complement of number and then returns the 2’s complement of result.

var a=~5; //result is -6

### 5)Left Shift ( << )

Left Shift operator is used to shift bits to left side. The left shift operator shifts bits to left and adds zeros to right side.

var a=5<<2; //result is 20

### 6)Right Shift (Sign Propogation)( >> )

Right Shift operator is used to shift bits to right side. The right shift operator shifts bits to right and adds sign bit to left side.

if number is positive then 0’s are filled to left side

if number is negative then 1’s are filled to left side

var a=5>>2; // result is 1

### 7)Right Shift (Zero fill) ( >>> )

Right Shift operator is used to shift bits to right side. The right shift operator shifts bits to right and adds zerosĀ to left side.

var a=5>>>2;//result is 1