JavaScript Bitwise Operators
Working with binary representations of numbers
🔢 What are Bitwise Operators?
Bitwise operators work on the binary representation of numbers. They perform operations on individual bits and are useful for low-level programming and optimization.
// Binary representation example
let a = 5; // 101 in binary
let b = 3; // 011 in binary
console.log(a & b); // 1 (001 in binary)
Output:
1
JavaScript Bitwise Operators
AND (&)
Returns 1 if both bits are 1
5 & 3 // 1 (101 & 011 = 001)
OR (|)
Returns 1 if at least one bit is 1
5 | 3 // 7 (101 | 011 = 111)
XOR (^)
Returns 1 if bits are different
5 ^ 3 // 6 (101 ^ 011 = 110)
NOT (~)
Inverts all bits
~5 // -6 (inverts all bits)
🔹 Shift Operators
Shift operators move bits left or right:
let num = 5; // 101 in binary
// Left shift (<<) - multiply by 2^n
console.log(num << 1); // 10 (1010 in binary)
console.log(num << 2); // 20 (10100 in binary)
// Right shift (>>) - divide by 2^n
console.log(num >> 1); // 2 (10 in binary)
console.log(num >> 2); // 1 (1 in binary)
// Unsigned right shift (>>>)
console.log(-5 >>> 1); // 2147483645
Output:
10
20
2
1
2147483645
20
2
1
2147483645
🔹 Practical Examples
Common uses of bitwise operators:
// Check if number is even or odd
function isEven(num) {
return (num & 1) === 0;
}
console.log(isEven(4)); // true
console.log(isEven(5)); // false
// Toggle a bit
let flags = 5; // 101
flags ^= 2; // Toggle bit at position 1
console.log(flags); // 7 (111)
// Set a bit
flags |= 8; // Set bit at position 3
console.log(flags); // 15 (1111)
// Clear a bit
flags &= ~4; // Clear bit at position 2
console.log(flags); // 11 (1011)
Output:
true
false
7
15
11
false
7
15
11