Learn JavaScript
❯ operators.op_bitwise

Bitwise Operators in JavaScript

$concept

JavaScript bitwise operators (&, |, ^, ~, <<, >>, >>>) coerce operands to 32-bit ints, operate, and return signed 32-bit results (except >>>, which returns unsigned). They're niche in typical app code but essential in parsers, hashes, color math, and flags — plus the famous | 0 floor trick for non-negative numbers.

Know the two shifts: >> preserves sign (arithmetic), >>> zero-fills (logical) — -8 >> 1 is -4 while -8 >>> 1 is 2147483644. Beyond 32 bits, operands silently truncate — BigInt has its own bitwise set for big-integer bit work.

$how it works
1

32-bit coercion

Operands convert via ToInt32 first — 2^32 wraps, fractions truncate, huge numbers lose high bits.

2

>> vs >>>

Arithmetic >> keeps the sign bit; logical >>> zero-fills — the difference matters only for negatives.

3

Flags and masks

Same idioms as C: test (f & READ), set (f |= W), clear (f &= ~X) — permission and option bitfields.

4

| 0 floors positives

x | 0 truncates toward zero for in-range positives — terse, fast, and cryptic to the uninitiated (comment it).

$example
console.log(5 & 3, 5 | 3, 5 ^ 3);
console.log(1 << 3, -8 >> 1);
Output
1 7 6
8 -4
1101 & 011 = 001 (1); OR merges to 111 (7); XOR flags differences as 110 (6).
21 << 3 multiplies to 8; arithmetic -8 >> 1 halves toward negative infinity to -4.
3All results are signed 32-bit ints — the operators' fixed universe.
$use cases
Flag fields with test/set/clear one-liners
Hash functions and color packing with shifts and masks
| 0 flooring in hot numeric code (with explanatory comments)
>>> for unsigned interpretation of negative bit patterns

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.