Sub topic 18
Bitwise and Shift Operators
This chapter assumes you already know how ToNumber converts values (from the coercion chapter) and how arithmetic operators treat their operands. Bitwise operators are rare in everyday JavaScript. They do show up in permission flags, hashing, binary protocols, and old code that relies on tricks like x | 0. The rules are simple, but they can surprise you because JavaScript numbers are 64-bit floating-point values, and bitwise operators work on something else.
The Working Model: Everything Becomes a 32-bit Integer
A bitwise operator works on the individual bits of an integer. JavaScript has no integer type for ordinary numbers, so every bitwise operator converts its operands before it does any work:
- Each operand goes through
ToNumber, so'5'becomes5and'12px'becomesNaN. - The result is converted with
ToInt32.NaNand±Infinitybecome0. Other values are truncated toward zero and then wrapped modulo 2³² into the signed range −2,147,483,648 to 2,147,483,647. - The operator works on those 32 bits in two's complement form.
- The result is converted back to an ordinary Number.
The unsigned right shift >>> is the one exception. It converts its left operand with ToUint32, so its result is always between 0 and 4,294,967,295.
The Operators
| Operator | Name | Result bit is 1 when | Example | Column | Column |
|---|---|---|---|---|---|
| `a & b` | AND | both bits are 1 | `5 & 3` is `1` | ||
| `a \ | b` | OR | either bit is 1 | `5 \ | 3` is `7` |
| `a ^ b` | XOR | exactly one bit is 1 | `5 ^ 3` is `6` | ||
| `~a` | NOT | the bit was 0 | `~5` is `-6` | ||
| `a << n` | Left shift | bits move left, zeros fill in | `1 << 3` is `8` | ||
| `a >> n` | Sign-propagating right shift | bits move right, the sign bit is copied in | `-16 >> 2` is `-4` | ||
| `a >>> n` | Zero-fill right shift | bits move right, zeros fill in | `-1 >>> 0` is `4294967295` |
console.log(5 & 3); // 1 (101 & 011 = 001)
console.log(5 | 3); // 7 (101 | 011 = 111)
console.log(5 ^ 3); // 6 (101 ^ 011 = 110)
console.log(~5); // -6 (~x is always -(x + 1))
console.log(1 << 3); // 8
console.log(-16 >> 2); // -4
console.log(-1 >>> 0); // 4294967295Under two's complement, ~x always equals -(x + 1). That is why ~5 is -6 and ~-1 is 0.
A Practical Use: Flags
Bit flags pack several yes/no settings into a single number. Each flag gets its own bit, built with a left shift:
const READ = 1 << 0; // 1 (001)
const WRITE = 1 << 1; // 2 (010)
const EXEC = 1 << 2; // 4 (100)
const has = (perms, flag) => (perms & flag) !== 0;
let perms = READ | WRITE; // 3: turn on two flags
console.log(has(perms, WRITE)); // true
console.log(has(perms, EXEC)); // false
perms |= EXEC; // 7: turn a flag on
perms &= ~WRITE; // 5: turn a flag off
perms ^= READ; // 4: toggle a flag
console.log(perms.toString(2)); // '100'The compound forms &=, |=, ^=, <<=, >>= and >>>= work like +=. They compute the result and assign it back.
Gotcha: Truncation and Wrapping
Developers often write x | 0 or ~~x to "convert to an integer". It truncates toward zero, which differs from Math.floor for negative numbers. It also breaks silently once a value no longer fits in 32 bits.
console.log(3.7 | 0); // 3
console.log(-3.7 | 0); // -3
console.log(Math.floor(-3.7)); // -4
console.log(Math.trunc(-3.7)); // -3
console.log(~~'12.9'); // 12
console.log('12px' | 0); // 0: Number('12px') is NaN, and NaN becomes 0
console.log(2 ** 31 | 0); // -2147483648: wrapped into the negative range
console.log(2 ** 32 | 0); // 0
console.log(Date.now() | 0); // a meaningless number: timestamps exceed 32 bitsGotcha: Shift Counts Are Masked
The right operand of a shift is converted with ToUint32, and only its lowest 5 bits are used (n & 31). So shifting by 32 is the same as shifting by 0.
console.log(1 << 31); // -2147483648: the 1 lands in the sign bit
console.log(1 << 32); // 1: the count 32 becomes 0
console.log(1 << 33); // 2: the count 33 becomes 1
console.log(-16 >> 2); // -4: the sign is preserved
console.log(-16 >>> 2); // 1073741820: -16 is read as 4294967280 first
console.log((-1 >>> 0).toString(2).length); // 32x >>> 0 is the standard idiom for reading a value as an unsigned 32-bit integer. Hash functions use it to keep results non-negative.
Gotcha: Precedence Below Equality
&, ^ and | have lower precedence than === and ==. In C-family languages this is a well-known trap, and JavaScript inherits it. Shifts behave differently: they bind tighter than relational operators.
const n = 4;
console.log(n & 1 === 0); // 0: parsed as n & (1 === 0), which is 4 & false
console.log((n & 1) === 0); // true: n is even
console.log(1 << 2 < 5); // true: parsed as (1 << 2) < 5The full order from tightest to loosest is: ~ (unary), shifts, relational, equality, &, ^, |, then && and ||. When you mix a bitwise operator with a comparison, always add parentheses.
Gotcha: The `~indexOf` Idiom
Older code tests membership with ~arr.indexOf(x). This works because indexOf returns -1 when nothing is found, and ~-1 is 0, which is falsy.
const list = ['a', 'b'];
console.log(~list.indexOf('b')); // -2 (truthy)
console.log(~list.indexOf('z')); // 0 (falsy)
console.log(list.includes('z')); // false: clearer, and it finds NaN tooUse includes in new code. It states the intent, and it uses SameValueZero, so it finds NaN.
Bitwise Operators and BigInt
Every bitwise operator except >>> also works on BigInt values, at any width and without 32-bit truncation. Mixing a BigInt and a Number throws a TypeError, and >>> on a BigInt always throws because BigInts have no fixed width. The next chapter covers BigInt operators in full.
console.log(1n << 40n); // 1099511627776n: no 32-bit limit
console.log(1 << 40); // 256: the count 40 is masked to 8
try {
1n >>> 0n;
} catch (e) {
console.log(e instanceof TypeError); // true
}When to Use Them
Use bitwise operators for flags, binary formats, typed-array work, and hashing, where the 32-bit model is what you need. Do not use them for rounding, for membership tests, or for any value that could go past 2³¹ − 1.
Exercise
What does (2 ** 32 + 5) | 0 evaluate to, and why?
Show answer
It evaluates to 5. ToInt32 wraps the value modulo 2^32, so 4294967301 becomes 5 before the OR with 0.
Exercise
A developer writes if (flags & WRITE === WRITE) and it never behaves correctly. Explain the bug and fix it.
Show answer
=== has higher precedence than &, so the condition is parsed as flags & (WRITE === WRITE), which is flags & true, which is flags & 1. That tests the READ bit. Write if ((flags & WRITE) === WRITE) instead.
Exercise
Predict the output of console.log(-3.5 | 0, -1 >>> 28, 1 << 64).
Show answer
It prints -3 15 1. -3.5 | 0 truncates toward zero to -3. -1 >>> 28 reads -1 as 4294967295 (32 one-bits) and shifts right by 28, which leaves four one-bits, 15. 1 << 64 masks the count to 64 & 31 = 0, so the result is 1.