JavaScript — Bitwise
Bits, not values
Bitwise operators convert operands to signed 32-bit integers and operate bit-by-bit:
5 → 0101
3 → 0011
The six operators
| Op | Name | Rule | Example |
|---|---|---|---|
& | AND | 1 if BOTH bits are 1 | 5 & 3 → 0001 = 1 |
| | OR | 1 if EITHER is 1 | 5 | 3 → 0111 = 7 |
^ | XOR | 1 if bits DIFFER | 5 ^ 3 → 0110 = 6 |
~ | NOT | flips all 32 bits | ~5 = -6 (~n === -(n+1)) |
<< | left shift | move left, fill 0s | 5 << 1 = 10 (×2) |
>> | right shift | move right, keep sign | 10 >> 1 = 5 |
>>> | unsigned right | fill with 0s | differs on negatives |
Binary helpers for exploring
(6).toString(2); // "110"
parseInt("110", 2); // 6
The practical payoff: bitmasks
Pack many booleans into one integer:
const READ = 1; // 001
const WRITE = 2; // 010
const ADMIN = 4; // 100
let perms = READ | WRITE; // grant: 011
perms & READ // check: truthy ✓
perms & ADMIN // 0 ✗
perms |= ADMIN // add a flag
perms &= ~ADMIN // remove it
perms ^= WRITE // toggle it
One number, many independent flags — file permissions, game states, config options.
Always parenthesize comparisons:
(perms & READ) !== 0— precedence bites.
Bitwise ≠ logical
a & b // bits a && b // boolean logic/truthiness
a | b // bits a || b // fallback semantics
Different worlds despite similar glyphs.
Limitations
- 32-bit ceiling: big numbers corrupt silently —
(2**40 | 0)is garbage. Use BigInt beyond that. - Readability cost: future-you must decode intent; comment masks well or use named constants.
Where you'll actually see them
- Permission systems (as above)
- Parsers/codecs reading binary formats
- Hash functions & graphics code
- Interview puzzles (single-number XOR trick:
pairs XORed cancel, leaving the unique one)
For everyday app code, plain objects/arrays of flags usually communicate better.
Mini Practice
- Print binary forms of 5–12 via toString(2).
- Hand-compute then verify &, |, ^ for two numbers.
- Prove
~n === -(n+1)for five values. - Shifts: multiply/divide by 2 four ways.
- Build a 4-flag permission system: grant, test, revoke, toggle.
- Show the 32-bit overflow failure with a huge number.
Next: popup boxes →
Related Topics
Frequently Asked Questions about Bitwise
What is Bitwise in JavaScript?
Bitwise is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Bitwise?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Bitwise.
Why is Bitwise important in JavaScript?
Bitwise is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.