Bitwise Operations in JavaScript

In bitwise operations, the operands are treated as 32 bit binary digits (0s and 1s) and then the actions (AND, OR etc.) are performed.

Bitwise AND Operator: "&"

				
					let a = 100
let b = 200
let c = a & b //Bitwise AND Operation
console.log(c)

Output:-> 64

How does it work?

100 and 200 will first be converted to their 32 bits binary equivalent and then the AND operation is performed.
100 to binary => 01100100
200 to binary => 11001000
01100100 & 11001000 => 01000000
01000000 to decimal => 64 //Output

Note: In Line 11 and 12 preceding zeros in binary equivalent are skipped just for simplicity and ease of understanding of the example.
				
			

Bitwise OR Operator: "|"

				
					let a = 100
let b = 200
let c = a | b //Bitwise OR Operation
console.log(c)

Output:-> 236

How does it work?

100 and 200 will first be converted to their 32 bits binary equivalent and then the OR operation is performed.
100 to binary => 01100100
200 to binary => 11001000
01100100 | 11001000 => 11101100
11101100 to decimal => 236 //Output

Note: In Line 11 and 12 preceding zeros in binary equivalent are skipped just for simplicity and ease of understanding of the example.
				
			

Bitwise XOR Operator: "^"

				
					let a = 100
let b = 200
let c = a ^ b //Bitwise XOR Operation
console.log(c)

Output:-> 172

How does it work?

100 and 200 will first be converted to their 32 bits binary equivalent and then the XOR operation is performed.
100 to binary => 01100100
200 to binary => 11001000
01100100 ^ 11001000 => 10101100
10101100 to decimal => 172 //Output

Note: In Line 11 and 12 preceding zeros in binary equivalent are skipped just for simplicity and ease of understanding of the example.
				
			

Bitwise NOT Operator: "~"

				
					let a = 10
let b = ~a //Bitwise NOT Operation
console.log(b)

Output:-> -11

How does it work?

10 will first be converted to its 32 bits binary equivalent and then the NOT operation is performed.
10 to binary => 00000000000000000000000000001010
~00000000000000000000000000001010 => 11111111111111111111111111110101
11111111111111111111111111110101 to decimal from signed 2's compliment => -11 //Output