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

Bitwise XOR (^)

Understand the exclusive OR operator that returns 1 only when bits differ.

What You'll Learn

You'll discover how the XOR (exclusive OR) operator compares bits and returns 1 only when they differ.

Understanding XOR Logic

The Bitwise XOR operator (^) compares two numbers bit-by-bit and returns a result where each bit is 1 if the corresponding bits in the two operands are different, and 0 if they're the same.

Think of it like a light switch controlled by two people. The light is only ON (1) when exactly one person has their switch flipped, but OFF (0) when both switches match (both on or both off).

How XOR Works

Here's the truth table for a single bit:

0 ^ 0 = 0  (same → 0)
0 ^ 1 = 1  (different → 1)
1 ^ 0 = 1  (different → 1)
1 ^ 1 = 0  (same → 0)

When you use XOR on numbers, JavaScript converts them to 32-bit binary and applies this logic to each bit position:

5 ^ 3
// 5 = 0101
// 3 = 0011
//     ----
//     0110 = 6
12 ^ 7
// 12 = 1100
//  7 = 0111
//      ----
//      1011 = 11

Interesting XOR Properties

XOR has some unique characteristics:

let x = 10;
x ^ x; // Always 0 (anything XOR itself equals 0)
x ^ 0; // Always x (XOR with 0 preserves the value)

Key Takeaway: The XOR operator (^) returns 1 for each bit position where the two operands differ, making it useful for detecting differences and performing clever bit manipulations.