Bitwise Operators
Overview
Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones), rather than as decimal, hexadecimal, or octal numbers. They perform operations directly at the CPU level on these binary representations.
While rarely used in high-level web development (React/Angular), they are crucial in performance-critical code, cryptography, graphics processing, and algorithmic problem solving.
Syntax
// 5 in binary is 0101
// 1 in binary is 0001
// Bitwise AND (&): Sets bit to 1 if BOTH bits are 1
console.log(5 & 1); // 1 (0001)
// Bitwise OR (|): Sets bit to 1 if ONE of two bits is 1
console.log(5 | 1); // 5 (0101)
// Bitwise XOR (^): Sets bit to 1 if ONLY ONE of two bits is 1
console.log(5 ^ 1); // 4 (0100)
// Bitwise NOT (~): Inverts all the bits
console.log(~5); // -6let a = 5; // 00000000000000000000000000000101
// Left Shift (<<): Shifts bits left, effectively multiplying by 2^n
console.log(a << 1); // 10
// Right Shift (>>): Shifts bits right, effectively dividing by 2^n
console.log(a >> 1); // 2Common Pitfalls
- JavaScript numbers are stored as 64-bit floating-point numbers. However, bitwise operators convert them to 32-bit integers before operating, which can lead to unexpected truncation and loss of precision on very large numbers.
Interview Questions
By using Bitwise AND: num & 1. If (num & 1) === 1, the number is odd. If it equals 0, the number is even. This is marginally faster than the modulo operator.
Real-World Example
Managing a complex set of user permissions using Bitmasks. Instead of having 5 boolean columns in a database, you store a single integer where each bit represents a permission (e.g., READ = 1, WRITE = 2, EXECUTE = 4).
const READ = 1; // 001
const WRITE = 2; // 010
const EXEC = 4; // 100
let myPermissions = READ | WRITE; // 3 (011)
// Check if I have write permission
const canWrite = (myPermissions & WRITE) === WRITE; // trueCheck Your Knowledge
Test your understanding of Bitwise Operators with these quick questions.