skip to content

In JavaScript, what do `x | 0` and `~~x` do to `7.9`, `-7.9`, `3000000000` and `NaN`, and why are they unsafe as truncation?

level: middleimportance: should knowfreq 44%

answer

  1. bitwise means 32 bits first
  2. truncate toward zero, then keep low bits
  3. the top bit reads as a sign
  4. bad input turns into a plausible number
  5. compare with Math.trunc

basics

~20 s

x | 0 and ~~x both apply ToInt32: 7.9 becomes 7, -7.9 becomes -7, 3000000000 wraps to -1294967296 and NaN becomes 0. They are unsafe because values outside the signed 32-bit range wrap silently and bad input turns into 0.

solid answer

~50 s

Every bitwise operator on numbers first runs its operands through ToInt32, and `x | 0` and `~~x` expose that conversion because OR with `0` and a double NOT change nothing else. ToInt32 makes `NaN` and the infinities `0`, truncates toward zero, then keeps the low 32 bits and reads them as two's complement. So `7.9` gives `7`, `-7.9` gives `-7`, `3000000000` wraps to `-1294967296` and `NaN` gives `0`. They look like `Math.trunc`, which is why they survive in older code, but they agree with it only while the truncated value fits in -2147483648 to 2147483647. Outside that range a file size or a millisecond timestamp silently becomes a wrong number, and a failed parse becomes a plausible `0` rather than `NaN`. In review I ask for `Math.trunc`, and accept the bitwise form only where 32-bit wrapping is the intent, as in a hash.

code

javascript · 8 lines
javascript
const fileSize = 3221225472; // 3 GiB

console.log(fileSize | 0);         // -1073741824
console.log(Math.trunc(fileSize)); // 3221225472

const parsed = Number("abc");
console.log(parsed | 0);         // 0
console.log(Math.trunc(parsed)); // NaN

go deeper

for a junior

Know that bitwise operators turn numbers into 32-bit integers, so 7.9 | 0 drops the fraction, and that this is not a general replacement for Math.trunc or Math.floor.

for a middle

Walk through ToInt32 from coercion to two's complement, predict the wrap for values above 2147483647, and explain what NaN and the infinities become and why that hides bad input.

for a senior

Treat the idiom as a review flag on anything that can pass 32 bits, such as timestamps, sizes and counters. Separate that from code where wrapping is the point, and know when Math.imul is the correct tool.

for a principal

Whether to forbid bitwise truncation through a lint rule with a local exception for hashing and binary formats is a cheap standing decision, and it removes a recurring class of silent numeric bugs.

## The conversion behind every bitwise operator A JavaScript `number` is a 64-bit floating-point value, but the bitwise operators `&`, `|`, `^`, `~`, `<<` and `>>` work on **32-bit signed integers**. So before doing anything else they convert each number operand with an abstract operation the specification calls **ToInt32**: 1. Coerce the operand to a number. `'12'` becomes `12`, `null` becomes `0`, and `'abc'` and `undefined` become `NaN`. 2. If the number is `NaN`, `0`, `-0`, `Infinity` or `-Infinity`, the answer is `0`. 3. Otherwise truncate toward zero, dropping the fraction. 4. Keep the value modulo 2^32, which means keeping the low 32 bits. 5. Read those bits as **two's complement**: if the top bit is set, the value is negative, which is the same as subtracting 2^32. The result always lies between -2147483648 and 2147483647. Nothing is clamped to those limits. The value wraps around. ## Worked values | Expression | Result | Why | |---|---|---| | `7.9 \| 0` | `7` | fraction dropped | | `-7.9 \| 0` | `-7` | truncation goes toward zero | | `2147483647 \| 0` | `2147483647` | largest value that survives | | `2147483648 \| 0` | `-2147483648` | top bit is now the sign | | `3000000000 \| 0` | `-1294967296` | 3000000000 minus 2^32 | | `4294967296 \| 0` | `0` | low 32 bits are all zero | | `1e10 \| 0` | `1410065408` | high bits discarded | | `NaN \| 0`, `Infinity \| 0` | `0` | step 2 | | `'abc' \| 0` | `0` | coerces to `NaN`, then step 2 | ## Why `| 0` and `~~` expose it OR with `0` leaves every bit as it was, so the only visible effect of `x | 0` is the conversion. The same holds for `~~x`: `~` converts and flips every bit, and the second `~` flips them back, so what remains is the converted value. `x ^ 0`, `x >> 0` and `x << 0` behave the same way. The single `~` is useful to know on its own. For any 32-bit integer, `~n` equals `-(n + 1)`, so `~5` is `-6` and `~-1` is `0`. That second fact produced an old idiom, `if (~list.indexOf(item))`, which relies on `indexOf` returning `-1` when nothing is found. `includes` says the same thing directly. ## Compared with the `Math` functions | Input | `x \| 0` | `Math.trunc(x)` | `Math.floor(x)` | |---|---|---|---| | `7.9` | `7` | `7` | `7` | | `-7.9` | `-7` | `-7` | `-8` | | `3000000000.5` | `-1294967296` | `3000000000` | `3000000000` | | `NaN` | `0` | `NaN` | `NaN` | Two rows carry the lesson. `| 0` is not floor, because it goes toward zero on negatives. And `Math.trunc` lets `NaN` through, so a bad value stays visibly bad, where `| 0` hides it as an ordinary `0`. A smaller difference: `Math.trunc(-0.5)` is `-0`, while `-0.5 | 0` is `0`, because a 32-bit integer has no negative zero. ## Where wrapping is what you want The conversion is the right tool when 32-bit arithmetic is the requirement: - **Bit flags**, where `(flags & WRITE) !== 0` tests one bit and every value is small by design. - **Non-cryptographic hashes**, where wrapping on every step keeps the value bounded. - **Binary formats**, where a field's width is exactly what the specification says it is. ```javascript function hash(text) { let h = 0; for (const ch of text) { h = (h * 31 + ch.charCodeAt(0)) | 0; } return h; } console.log(hash("hello")); // 99162322 console.log(Math.imul(0xffffffff, 0xffffffff)); // 1 console.log((0xffffffff * 0xffffffff) | 0); // 0 ``` Here `h * 31` stays well inside the range a double holds exactly, so `| 0` wraps a precise value. With two large factors the double product has already lost its low bits, as the last two lines show, and that is what `Math.imul` is for. ## Reading it in review - `Date.now() | 0` or `size | 0` is a bug as soon as the value passes 2147483647. A `Date.UTC(2026, 10, 3)` timestamp comes out as `-1632329728`. - `~~(a / b)` on an average of large values wraps, so `(3e9 + 3e9 + 2) / 2 | 0` gives `-1294967295`. - `parsed | 0` on user input turns garbage into `0`, which then looks valid downstream. - `x >> 0` and `x << 0` are the same conversion in a different spelling, so they deserve the same question. - Any speed argument for the bitwise form needs a measurement, and it does not excuse the wrap. The question to ask of each one is whether the value can ever pass 2147483647, and whether a wrong number or a `NaN` would be the better failure.

  • How does `~~x` differ from `Math.floor(x)` on a negative number?
    `~~x` truncates toward zero and `Math.floor` rounds down, so `~~-7.9` is `-7` while `Math.floor(-7.9)` is `-8`. The closer comparison is `Math.trunc(-7.9)`, also `-7`, although `Math.trunc` keeps its answer correct beyond 32 bits and leaves `NaN` as `NaN`.
  • What does a single `~n` compute, and why did `if (~s.indexOf(q))` work as a presence test?
    For a 32-bit integer, `~n` equals `-(n + 1)`, because flipping every bit in two's complement does exactly that. `indexOf` returns `-1` when nothing is found, `~-1` is `0`, and `0` is falsy, while every real index gives a non-zero result. `includes` now says this directly, so ask for it in review.
  • Why might `(a * b) | 0` give the wrong 32-bit product when `Math.imul(a, b)` gives the right one?
    The multiplication happens first, as a double. Once the exact product needs more than 53 bits, its low bits are already rounded away, and ToInt32 keeps exactly those bits. `(0xffffffff * 0xffffffff) | 0` gives `0`, while `Math.imul(0xffffffff, 0xffffffff)` gives the true low word, `1`.

  • x | 0 is simply a faster way to write Math.floor(x)
  • x | 0 clamps large values to the 32-bit limit instead of wrapping
  • NaN | 0 stays NaN, so bad input remains visible
  • Bitwise operators work on the full 64 bits of a JavaScript number
  • ~~x is safe on any value that fits in a Number