JS BigInt
BigInt stores arbitrarily large integers — beyond Number.MAX_SAFE_INTEGER (2⁵³ − 1). Use it for IDs, timestamps in nanoseconds, large counters, cryptography.
Two ways to make one
JS
const big = 9007199254740993n; // literal — trailing `n`
const fromNum = BigInt(42); // from a number
const fromStr = BigInt("1234567890123456789");
Arithmetic
JS
2n + 3n // 5n 10n / 3n // 3n ← truncated integer division 10n % 3n // 1n 2n ** 64n // 18446744073709551616n // Comparison works across types 1n < 2 // true 1n === 1 // false — different types 1n == 1 // true — loose equality coerces
Mixing with Number — don't
JS
1n + 1 // TypeError — can't mix 1n + BigInt(1) // 2n ✓ Number(1n) + 1 // 2 ✓ (loses precision for huge values)
Where BigInt shines
| Use case | Why |
|---|---|
| Database BIGINT columns | 64-bit IDs exceed safe Number range. |
| High-precision timestamps | performance.now() nanoseconds, process.hrtime.bigint(). |
| Crypto operations | Large modular arithmetic. |
| Game/sim state with no float drift | Exact integer math. |
JSON support
JS
JSON.stringify({ id: 1n }); // TypeError — no native JSON support
JSON.stringify({ id: 1n.toString() }); // ✓ workaround
// or use a custom replacer
Tip: BigInt is for integers only. There's no
BigFloat — use a decimal library or scaled integers if you need precise fractions.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS BigInt!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Write a BigInt literal for 1024.
const big = 1024
;
A single letter suffix.
Discussion
Loading…