Course contentsShow
← JavaScript
Lesson 262 of 2,7237. Arithmetic and OperatorsFree lesson

Common Bitwise Patterns

Explore practical uses like checking even/odd, swapping values, and toggling flags.

Common Bitwise Patterns

You'll learn practical everyday uses of bitwise operators that make your code more efficient.

While bitwise operators might seem abstract, they shine in specific patterns that solve common problems elegantly. These patterns are faster than traditional arithmetic approaches and appear frequently in real-world code.

Checking Even or Odd

The bitwise AND with 1 checks the least significant bit. If it's 0, the number is even; if 1, it's odd:

let num = 7;
let isOdd = (num & 1) === 1;  // true
let isEven = (num & 1) === 0; // false

Think of it like checking if the last light in a row is on (odd) or off (even).

Swapping Two Values Without a Temporary Variable

Using XOR three times swaps values:

let a = 5;
let b = 9;
a = a ^ b;
b = a ^ b;  // Now b = 5
a = a ^ b;  // Now a = 9

This works because XOR "remembers" differences between values.

Toggling a Flag

XOR flips a specific bit on or off:

let flags = 5;       // Binary: 101
flags = flags ^ 1;   // Toggle last bit: 100 (4)
flags = flags ^ 1;   // Toggle again: 101 (5)

Perfect for switching states like on/off or true/false without conditionals.

Checking If a Number is a Power of Two

Powers of two have exactly one bit set. Using n & (n - 1) clears that bit:

let num = 8;
let isPowerOfTwo = (num > 0) && ((num & (num - 1)) === 0);  // true

Key Takeaway: Bitwise patterns like checking parity with & 1, swapping with XOR, and toggling flags provide fast, elegant solutions to common programming tasks.