Sub topic 19
Operators and BigInt
This chapter assumes you already know how arithmetic operators convert their operands, how == differs from ===, and how Object.is and SameValueZero treat special values. It also assumes you can run code in Node.js or a browser console. BigInt is the primitive type for integers of any size. Its literals end in n, as in 42n. Most operators work on BigInt, but they follow a stricter rule than the Number rules you have seen so far: arithmetic never converts types for you.
Why BigInt Has Its Own Rules
A Number is a 64-bit floating-point value. It represents integers exactly only up to Number.MAX_SAFE_INTEGER (2^53 − 1). Above that limit, neighbouring integers collapse into the same value. BigInt has no such limit.
console.log(2 ** 53 === 2 ** 53 + 1); // true: precision lost
console.log(2n ** 53n === 2n ** 53n + 1n); // false: exact
console.log(BigInt(Number.MAX_SAFE_INTEGER) + 2n); // 9007199254740993nArithmetic that mixed the two types would have to choose a result type. Converting to Number could lose digits silently, and converting a fractional Number to BigInt could lose the fraction. The language designers refused to guess, so mixed arithmetic throws a TypeError.
Arithmetic Operators
When both operands are BigInt, +, -, *, /, %, and ** behave as integer arithmetic.
console.log(1n + 2n); // 3n
console.log(7n / 2n); // 3n: truncates toward zero
console.log(-7n / 2n); // -3n, not -4n
console.log(-7n % 2n); // -1n: remainder takes the sign of the dividend
console.log(2n ** 64n); // 18446744073709551616nDivision truncates toward zero, the same way Math.trunc does. It does not round down. If you need floor division for negative values, you have to adjust the result yourself.
Errors that Number arithmetic never throws
Number arithmetic falls back to Infinity or NaN. BigInt has neither value, so these cases throw a RangeError:
try { 1n / 0n; } catch (e) { console.log(e.name); } // RangeError
try { 2n ** -1n; } catch (e) { console.log(e.name); } // RangeError
try { 1n + 1; } catch (e) { console.log(e.name); } // TypeErrorUnary operators
Unary minus works on BigInt: -5n is a valid value. Unary plus throws a TypeError. The reason is that a lot of existing code assumes +x always produces a Number (for example asm.js), and the language preserves that guarantee.
console.log(-5n); // -5n
let i = 1n;
i++;
console.log(i); // 2n
try { +1n; } catch (e) { console.log(e.name); } // TypeErrorThe ++ and -- operators work too, and they keep the value a BigInt.
Comparison and Equality
Comparisons are allowed between BigInt and Number because a true/false answer cannot lose precision. The engine compares the mathematical values exactly. It does not convert one side first.
console.log(1n == 1); // true
console.log(1n === 1); // false: different types
console.log(1n == '1'); // true: the string is parsed as a BigInt
console.log(2n > 1); // true
console.log(1n < 1.5); // true
console.log(9007199254740993n == 2 ** 53 + 1); // false: the Number is really 2^53
console.log(Object.is(0n, -0n)); // true: BigInt has no negative zeroThe second-to-last line shows why exact comparison matters. 2 ** 53 + 1 evaluates to the Number 9007199254740992. The BigInt is one larger, and == reports that correctly.
Strict equality and SameValueZero never treat 1n and 1 as equal. This affects collections:
console.log([1n].includes(1)); // false
console.log(new Set([1n, 1]).size); // 2
const m = new Map([[1n, 'big']]);
console.log(m.get(1)); // undefinedBigInt also follows the truthiness rules: 0n is falsy and every other BigInt is truthy. typeof 10n returns 'bigint'.
Bitwise and Shift Operators
Number bitwise operators truncate to 32 bits. BigInt bitwise operators work on the full value and treat negatives as infinite two's complement.
console.log(5n & 3n); // 1n
console.log(~5n); // -6n
console.log(1n << 64n); // 18446744073709551616n (a Number would wrap: 1 << 64 is 1)
console.log(-16n >> 2n);// -4n
try { 5n >>> 1n; } catch (e) { console.log(e.name); } // TypeErrorThe unsigned right shift >>> throws because an infinitely wide value has no fixed top bit to fill with zero. To get fixed-width behaviour, use BigInt.asUintN or BigInt.asIntN:
console.log(BigInt.asUintN(64, -1n)); // 18446744073709551615n
console.log(BigInt.asIntN(8, 255n)); // -1nOperator Support at a Glance
| Operator | BigInt with BigInt | BigInt with Number | Column |
|---|---|---|---|
| `+ - * / % **` | Works, integer result | TypeError | |
| `+` with a string | Concatenates | Concatenates | |
| Unary `-`, `++`, `--` | Works | Not applicable | |
| Unary `+` | TypeError | Not applicable | |
| `& \ | ^ ~ << >>` | Works, arbitrary width | TypeError |
| `>>>` | TypeError | TypeError | |
| `< > <= >=`, `==` | Works | Works, exact comparison | |
| `===`, `Object.is` | Works | Always false |
Converting Explicitly
Because mixing types throws, you convert one side deliberately, and you choose where precision might be lost.
const big = 10n ** 20n;
console.log(Number(big)); // 100000000000000000000 (may be rounded)
console.log(BigInt(42) * 3n); // 126n
try { BigInt(1.5); } catch (e) { console.log(e.name); } // RangeError
console.log(BigInt(Math.trunc(1.5))); // 1nBigInt(x) throws on non-integer Numbers instead of rounding them. Number(big) never throws, but it rounds values above 2^53 without warning.
Common pitfalls
- Sort comparators such as
(a, b) => a - bthrow on arrays that mix BigInt and Number. Use(a, b) => (a < b ? -1 : a > b ? 1 : 0)instead, because<and>accept mixed types. Math.max(1n, 2n)throws a TypeError. TheMathfunctions only accept Numbers.JSON.stringify({ id: 1n })throws a TypeError. Convert the value to a string first, or pass a replacer function.- A check like
x === 0is always false whenxis0n. Compare against0n, or test truthiness with!x.
Exercise
Predict each result or error: (a) 9n / -2n, (b) 3n + '1', (c) 3n * 1, (d) 10n > 9.5, (e) [5n].indexOf(5), (f) 2n >>> 1n.
Show answer
(a) -4n, because division truncates toward zero (-4.5 becomes -4). (b) '31', because a string operand makes + concatenate. (c) TypeError, because BigInt and Number cannot be mixed in arithmetic. (d) true, because relational comparison between BigInt and Number is allowed and exact. (e) -1, because indexOf uses strict equality and 5n !== 5. (f) TypeError, because >>> is not defined for BigInt.
Exercise
Write a function average(values) that takes an array of BigInt values and returns their average as a BigInt rounded toward zero. Why can't you just call values.reduce((a, b) => a + b) / values.length?
Show answer
function average(values) { const sum = values.reduce((a, b) => a + b, 0n); return sum / BigInt(values.length); }. The reduce needs the initial value 0n, not 0, so the sum stays a BigInt. values.length is a Number, and dividing a BigInt by a Number throws a TypeError, so you must convert it with BigInt(values.length).