1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript BigInt Explained: Big Numbers, Division and JSON

JavaScript BigInt stores whole numbers of any size exactly, beyond the 2^53 limit where normal numbers start silently rounding. Learn when you need it, how arithmetic and division differ, why mixing types throws, how to send and receive big IDs through JSON without corruption, and what it costs in speed, with every example run in Node.js 24.

9 min read
JavaScript BigInt explained: big numbers, division and JSON

Key takeaways

  • JavaScript BigInt holds integers of any size exactly; write them with an n suffix, like 9007199254740993n.
  • Normal numbers lose precision above 9,007,199,254,740,991: in our run, 2**53 === 2**53 + 1 was true.
  • JSON.stringify throws on BigInt, and JSON.parse rounded the ID 9223372036854775807 to 9223372036854776000; a reviver using the new context.source argument kept it exact.
  • Ten million additions took 281 ms with BigInt versus 30 ms with Number.

JavaScript has one ordinary number type, a 64-bit floating-point value. It represents whole numbers exactly only up to 2^53 – 1. Beyond that, integers are silently rounded, which corrupts database IDs, tweet and order numbers, nanosecond timestamps, cryptographic values and large financial amounts in cents. JavaScript BigInt, added in ES2020, is a separate numeric type for integers of arbitrary size.

All examples ran in Node.js v24.22.1; every modern browser supports BigInt as well.

The 2^53 problem

Number.MAX_SAFE_INTEGER     // 9007199254740991
2 ** 53 + 1                 // 9007199254740992   (should end in 3)
2 ** 53 === 2 ** 53 + 1     // true

Floating-point numbers have 53 bits of precision for the digits. Once an integer needs more, the nearest representable value is used instead, and two different integers can compare equal. No error, no warning: the wrong number simply flows through your code. Use Number.isSafeInteger(x) to check whether a value is still exact.

Creating a BigInt

9007199254740993n                  // 9007199254740993n
typeof 10n                         // 'bigint'
BigInt("9007199254740993")         // 9007199254740993n   exact
BigInt(9007199254740993)           // 9007199254740992n   already rounded!
BigInt(1.5)                        // RangeError: The number 1.5 cannot be converted
                                   //   to a BigInt because it is not an integer

The n suffix creates a BigInt literal. BigInt() converts a string or a safe number. The trap is passing a large number literal: the literal is rounded to a Number before BigInt ever sees it, so the result was already wrong. Build large values from strings or n literals, never from unsafe numbers. There is no new BigInt(); it is called as a function.

Arithmetic

2n ** 64n          // 18446744073709551616n
function fact(n) { let r = 1n; for (let i = 2n; i <= n; i++) r *= i; return r; }
fact(30n)          // 265252859812191058636308480000000n
// same loop with Numbers: 2.6525285981219103e+32

+, -, *, ** and % work as expected and never overflow: memory is the only limit. Computing 30 factorial with BigInt gave all 33 digits; the Number version gave a rounded floating-point approximation.

Division rounds toward zero

7n / 2n      // 3n
-7n / 2n     // -3n
7n % 3n      // 1n

BigInt division drops the fractional part, rounding toward zero (so -3.5 becomes -3, not -4). That is the right behaviour for integer maths, and a common source of bugs when code written for Numbers is converted: total / count for an average silently loses the decimals. Scale values first, for example multiply by 100n before dividing, if you need fractional precision.

Mixing BigInt and Number throws

1n + 1             // TypeError: Cannot mix BigInt and other types, use explicit conversions
1n + BigInt(1)     // 2n
Math.max(1n, 2n)   // TypeError: Cannot convert a BigInt value to a number
+1n                // TypeError: Cannot convert a BigInt value to a number

JavaScript refuses to combine the two types implicitly, because either direction could lose information. Convert explicitly. The Math functions accept only Numbers, and unary plus is not allowed on BigInt (it would break code that expects +x to always return a Number). Write small helpers such as const max = (a, b) => (a > b ? a : b) instead.

Converting back to Number

Number(2n ** 64n)                 // 18446744073709552000
Number(12345678901234567890n)     // 12345678901234567000
Number(30n) / 100                 // 0.3

Number() converts a BigInt back, rounding to the nearest representable value. That is fine for display, charts or percentages, but never round-trip IDs this way. String(big) or big.toString() keeps every digit, and toLocaleString formats it: 12345678901234567890n.toLocaleString("en-US") gave 12,345,678,901,234,567,890.

Comparison, truthiness and sorting

1n == 1        // true    (loose equality compares values)
1n === 1       // false   (different types)
2n > 1         // true    (comparisons across types work)
0n ? "truthy" : "falsy"    // 'falsy'
[3n, 1, 2n].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))   // [ 1, 2n, 3n ]

Relational comparisons work between BigInt and Number, and 0n is falsy like 0. Strict equality treats them as different types, so Map keys and includes() checks will not match 1 with 1n. Never sort with (a, b) => a - b: subtraction returns a BigInt, and mixing it with Numbers throws. Use comparison operators as above; more sorting patterns are in our JavaScript array methods guide.

JSON.stringify throws on BigInt

JSON.stringify({ id: 1n })
// TypeError: Do not know how to serialize a BigInt

JSON.stringify({ id: 1n }, (k, v) => (typeof v === "bigint" ? v.toString() : v))
// '{"id":"1"}'

JSON has no BigInt type, so the built-in serialiser refuses rather than guessing. The usual fix is a replacer that converts BigInt to a string; the receiving side then knows to parse that field as a big number. Some codebases add a BigInt.prototype.toJSON method globally, but changing a built-in prototype affects every library in the program, so a replacer is safer. The same caution applies when copying data: see our deep copy guide for what structuredClone and JSON round trips keep.

JSON.parse without losing digits

const raw = '{"id": 9223372036854775807, "n": 1}';
JSON.parse(raw).id
// 9223372036854776000    corrupted

JSON.parse(raw, (k, v, ctx) => (k === "id" && ctx?.source ? BigInt(ctx.source) : v)).id
// 9223372036854775807n   exact

This is the bug that bites real APIs: a server written in Java, Go or Python sends a 64-bit ID as a JSON number, and the browser rounds it during parsing, before your code runs. Node 24 supports the newer JSON.parse source text access feature, which passes a third context argument to the reviver with the original text of each number, so the reviver can build an exact BigInt. Check browser support before relying on it in front-end code. The most robust fix is on the server: send large IDs as strings, a rule worth adding to your API design guidelines. Twitter’s API, for example, has long sent an id_str field next to the numeric ID for this reason. Our fetch API guide covers parsing responses in general.

Tip: treat any ID from another system as a string unless you need to do arithmetic on it. Strings never lose digits, compare fine for equality, and serialise without special code.

Bits, hex and fixed-width wrapping

BigInt.asUintN(64, -1n)    // 18446744073709551615n
BigInt.asIntN(8, 255n)     // -1n
(255n).toString(16)        // 'ff'
BigInt("0xff")             // 255n

Bitwise operators (&, |, ^, <<, >>) work on BigInt without the 32-bit limit that applies to Numbers. asUintN and asIntN wrap a value to a fixed bit width, which is how you emulate 64-bit unsigned integers from other languages, for hashing, binary protocols or BigUint64Array buffers. The unsigned right shift >>> is not available, because BigInt has no fixed width.

BigInt for money

0.1 + 0.2                  // 0.30000000000000004
10n + 20n                  // 30n   (amounts in cents)
Number(30n) / 100          // 0.3   (for display)

Storing currency as integer cents in BigInt removes floating-point rounding errors from sums, and avoids overflow for very large totals. Remember that division truncates, so handle rounding rules such as banker’s rounding explicitly. For most applications, ordinary Numbers holding integer cents are also safe up to about 90 trillion dollars; BigInt matters when values or precision go beyond that.

Performance

10M additions: Number 30 ms, BigInt 281 ms

BigInt values are heap objects with variable length, so engines cannot use plain CPU instructions for them. In our loop, BigInt was about nine times slower. That is irrelevant for IDs and occasional calculations, and important in tight numeric loops, where you should stay with Numbers whenever values are safe integers.

When to use BigInt

  • Use it for integers that can exceed 2^53: 64-bit database IDs, snowflake IDs, nanosecond timestamps from process.hrtime.bigint(), cryptography and exact large factorials or combinatorics.
  • Use strings for IDs you only store, compare and display.
  • Do not use it for decimals; BigInt has no fractional part. Use integer scaling or a decimal library.
  • Do not use it in hot numeric loops where safe Numbers are enough.

Database IDs grow faster than people expect; our auto increment guide explains why many tables switch to 64-bit keys, which is exactly when the front end needs BigInt or strings. For wrapping objects with custom behaviour instead, see the JavaScript Proxy guide.

Final thoughts

JavaScript BigInt fixes a real and silent problem: integers above 2^53 that quietly change value. Create big values from strings or n literals, convert explicitly between types, remember that division truncates, and handle JSON on both sides with a replacer and a reviver, or better, send big IDs as strings. Keep ordinary Numbers for fast everyday maths, and reach for BigInt whenever exactness matters more than speed.

Frequently asked questions

What is BigInt in JavaScript?

A numeric type for whole numbers of any size, written with an n suffix such as 10n. Unlike normal numbers, it stays exact beyond 9,007,199,254,740,991.

Why can I not add a BigInt and a Number?

JavaScript refuses to mix them implicitly because either conversion could lose information. Convert one side explicitly with BigInt or Number before the operation.

How do I convert a BigInt to JSON?

JSON.stringify throws on BigInt. Pass a replacer that turns BigInt values into strings, and parse those strings back into BigInt on the receiving side.

How do I parse large integers from JSON without losing precision?

Ask the server to send them as strings. Otherwise, in engines that support it, use a reviver that reads the original number text from its context argument and converts it with BigInt.

Is BigInt slower than Number?

Yes. In our Node 24 test, ten million additions took 281 ms with BigInt and 30 ms with Number, so use it only when values may exceed the safe integer range.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →