JavaScript - Bitwise Operations Part 2: Bitwise AND (&)
How the AND (&) Operator Works
The AND operator compares two binary numbers bit by bit and returns 1 only if both corresponding bits are 1. Otherwise, it returns 0.
Example 1: AND Operation
console.log(5 & 3); // Output: 1
Explanation:
Binary representation:
5 = 101
3 = 011
------------
Result = 001 (1 in decimal)
Only the last bit matches (1 & 1 = 1), so the result is 1.
Example 2: Using AND for Permissions
Bitwise AND is often used for permission checks.
const READ = 4; // 100
const WRITE = 2; // 010
const EXECUTE = 1; // 001
let userPermissions = READ | WRITE; // 100 | 010 = 110 (6)
console.log(userPermissions & READ); // 4 (has READ permission)
console.log(userPermissions & EXECUTE); // 0 (no EXECUTE permission)
Explanation:
userPermissions has READ and WRITE, but not EXECUTE.
AND (&) checks if a specific permission exists.