</>
Skip to content
JavaScript lessons (38/64)

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

OpNameRuleExample
&AND1 if BOTH bits are 15 & 3 → 0001 = 1
|OR1 if EITHER is 15 | 3 → 0111 = 7
^XOR1 if bits DIFFER5 ^ 3 → 0110 = 6
~NOTflips all 32 bits~5 = -6 (~n === -(n+1))
<<left shiftmove left, fill 0s5 << 1 = 10 (×2)
>>right shiftmove right, keep sign10 >> 1 = 5
>>>unsigned rightfill with 0sdiffers 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

  1. Print binary forms of 5–12 via toString(2).
  2. Hand-compute then verify &, |, ^ for two numbers.
  3. Prove ~n === -(n+1) for five values.
  4. Shifts: multiply/divide by 2 four ways.
  5. Build a 4-flag permission system: grant, test, revoke, toggle.
  6. 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.