{"id":13527082,"url":"https://github.com/tc39/proposal-bigint","last_synced_at":"2025-04-01T09:31:02.793Z","repository":{"id":64454680,"uuid":"80252584","full_name":"tc39/proposal-bigint","owner":"tc39","description":"Arbitrary precision integers in JavaScript","archived":true,"fork":false,"pushed_at":"2019-10-09T01:42:58.000Z","size":328,"stargazers_count":561,"open_issues_count":1,"forks_count":57,"subscribers_count":57,"default_branch":"master","last_synced_at":"2024-11-02T12:34:07.522Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://tc39.github.io/proposal-bigint","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tc39.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-01-27T22:46:46.000Z","updated_at":"2024-08-21T19:34:36.000Z","dependencies_parsed_at":"2022-12-17T21:37:30.771Z","dependency_job_id":null,"html_url":"https://github.com/tc39/proposal-bigint","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tc39%2Fproposal-bigint","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tc39%2Fproposal-bigint/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tc39%2Fproposal-bigint/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tc39%2Fproposal-bigint/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tc39","download_url":"https://codeload.github.com/tc39/proposal-bigint/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246615943,"owners_count":20806031,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T06:01:40.575Z","updated_at":"2025-04-01T09:31:02.467Z","avatar_url":"https://github.com/tc39.png","language":"HTML","funding_links":[],"categories":["HTML","Javascript"],"sub_categories":[],"readme":"# BigInt: Arbitrary precision integers in JavaScript\n\nDaniel Ehrenberg, Igalia. Stage 4\n\nThis proposal is complete and already merged into ECMA262 specification. See the specification text [here](https://tc39.es/ecma262/).\n\nThanks for help and feedback on this effort from Brendan Eich, Waldemar Horwat, Jaro Sevcik, Benedikt Meurer, Michael Saboff, Adam Klein, Sarah Groff-Palermo and others.\n\n## Contents\n1. [What Is It?](#what-is-it)\n2. [How Does It Work?](#how-does-it-work)\n\t- [Syntax](#syntax)\n\t- [Example: Calculating Primes](#example-calculating-primes)\n\t- [Operators](#operators)\n\t- [Comparisons](#comparisons)\n\t- [Conditionals](#conditionals)\n\t- [Other API Notes](#other-api-notes)\n3. [Gotchas \u0026 Exceptions](#gotchas--exceptions)\n\t- [Interoperation with `Number` and `String`](#interoperation-with-number-and-string)\n\t- [Rounding](#rounding)\n\t- [Cryptography](#cryptography)\n\t- [Other Exceptions](#other-exceptions)\n\t- [Usage Recommendations](#usage-recommendations)\n4. [About the Proposal](#about-the-proposal)\n\t- [Motivation, Or Why Do We Need Such Big Numbers?](#motivation-why-do-we-need-such-big-numbers)\n\t- [Design Philosophy, Or Why Is This Like This?](#design-goals-or-why-is-this-like-this)\n\t- [State of the Proposal](#state-of-the-proposal)\n\n\n## What Is It?\n\n`BigInt` is a new primitive that provides a way to represent whole numbers larger than 2\u003csup\u003e53\u003c/sup\u003e, which is the largest number Javascript can reliably represent with the `Number` primitive.\n\n```js\nconst x = Number.MAX_SAFE_INTEGER;\n// ↪ 9007199254740991, this is 1 less than 2^53\n\nconst y = x + 1;\n// ↪ 9007199254740992, ok, checks out\n\nconst z = x + 2\n// ↪ 9007199254740992, wait, that’s the same as above!\n```\n\n[Learn more about how numbers are represented in Javascript in the slides from Daniel's talk at JSConfEU.](https://docs.google.com/presentation/d/1apPbAiv_-mJF35P31IjaII8UA6TwSynCA_zhfDEmgOE/edit#slide=id.g38a1897a56_0_97) \n\n## How Does It Work?\n\nThe following sections show `BigInt` in action. A number have been influenced by or taken outright from [Mathias Bynens's BigInt v8 update, which includes more details than this page.](https://developers.google.com/web/updates/2018/05/bigint)\n\n### Syntax\n\nA `BigInt` is created by appending `n` to the end of the integer or by calling the constructor.\n\n```js\n\nconst theBiggestInt = 9007199254740991n;\n\nconst alsoHuge = BigInt(9007199254740991);\n// ↪ 9007199254740991n\n\nconst hugeButString = BigInt('9007199254740991');\n// ↪ 9007199254740991n\n\n```\n\n### Example: Calculating Primes\n\n```js\nfunction isPrime(p) {\n  for (let i = 2n; i * i \u003c= p; i++) {\n    if (p % i === 0n) return false;\n  }\n  return true;\n}\n\n// Takes a BigInt as an argument and returns a BigInt\nfunction nthPrime(nth) {\n  let maybePrime = 2n;\n  let prime = 0n;\n  \n  while (nth \u003e= 0n) {\n    if (isPrime(maybePrime)) {\n      nth -= 1n;\n      prime = maybePrime;\n    }\n    maybePrime += 1n;\n  }\n  \n  return prime;\n}\n\n```\n\n### Operators\n\nYou can use `+`, `*`, `-`, `**` and `%` with `BigInt`s, just like with `Number`s.\n\n```js\n\nconst previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);\n// ↪ 9007199254740991\n\nconst maxPlusOne = previousMaxSafe + 1n;\n// ↪ 9007199254740992n\n \nconst theFuture = previousMaxSafe + 2n;\n// ↪ 9007199254740993n, this works now!\n\nconst multi = previousMaxSafe * 2n;\n// ↪ 18014398509481982n\n\nconst subtr = multi – 10n;\n// ↪ 18014398509481972n\n\nconst mod = multi % 10n;\n// ↪ 2n\n\nconst bigN = 2n ** 54n;\n// ↪ 18014398509481984n\n\nbigN * -1n\n// ↪ –18014398509481984n\n\n```\n\nThe `/` operator also work as expected with whole numbers. However, since these are `BigInt`s and not `BigDecimal`s, this operation will round towards 0, which is to say, it will not return any fractional digits.\n\n```js\n\nconst expected = 4n / 2n;\n// ↪ 2n\n\nconst rounded = 5n / 2n;\n// ↪ 2n, not 2.5n\n\n```\n\n[See the advanced documentation for use with bitwise operators.](/ADVANCED.md)\n\n### Comparisons\n\nA `BigInt` is not strictly equal to a `Number`, but it is loosely so.\n\n```js\n\n0n === 0\n// ↪ false\n\n0n == 0\n// ↪ true\n\n```\n\n`Number`s and `BigInt`s may be compared as usual.\n\n```js\n1n \u003c 2\n// ↪ true\n\n2n \u003e 1\n// ↪ true\n\n2 \u003e 2\n// ↪ false\n\n2n \u003e 2\n// ↪ false\n\n2n \u003e= 2\n// ↪ true\n```\n\nThey may be mixed in arrays and sorted.\n\n```js\n\nconst mixed = [4n, 6, -12n, 10, 4, 0, 0n];\n// ↪  [4n, 6, -12n, 10, 4, 0, 0n]\n\nmixed.sort();\n// ↪ [-12n, 0, 0n, 10, 4n, 4, 6]\n```\n\n### Conditionals\n\nA `BigInt` behaves like a `Number` in cases where it is converted to a `Boolean`: `if`, `||`, `\u0026\u0026`, `Boolean`, `!`.\n\n```js\n\nif (0n) {\n  console.log('Hello from the if!');\n} else {\n  console.log('Hello from the else!');\n}\n\n// ↪ \"Hello from the else!\"\n\n0n || 12n\n// ↪ 12n\n\n0n \u0026\u0026 12n\n// ↪ 0n\n\nBoolean(0n)\n// ↪ false\n\nBoolean(12n)\n// ↪ true\n\n!12n\n// ↪ false\n\n!0n\n// ↪ true\n\n```\n\n### Other API Notes\n\n`BigInt`s may also be used in `BigInt64Array` and `BigUint64Array` [typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) for 64-bit integers.\n\n```js\nconst view = new BigInt64Array(4);\n// ↪ [0n, 0n, 0n, 0n]\nview.length;\n// ↪ 4\nview[0];\n// ↪ 0n\nview[0] = 42n;\nview[0];\n// ↪ 42n\n\n// Highest possible BigInt value that can be represented as a\n// signed 64-bit integer.\nconst max = 2n ** (64n - 1n) - 1n;\nview[0] = max;\nview[0];\n// ↪ 9_223_372_036_854_775_807n\nview[0] = max + 1n;\nview[0];\n// ↪ -9_223_372_036_854_775_808n\n//   ^ negative because of overflow\n\n```\n\n[For more about `BigInt` library functions, see the advanced section.](/ADVANCED.md)\n\n\n## Gotchas \u0026 Exceptions\n\n### Interoperation with `Number` and `String`\n\nThe biggest surprise may be that `BigInt`s cannot be operated on interchangeably with `Number`s. Instead a `TypeError` will be thrown. ([Read the design philosophy for more about why this decision was made.](#design-goals-or-why-is-this-like-this))\n\n\n```js\n\n1n + 2\n// ↪ TypeError: Cannot mix BigInt and other types, use explicit conversions\n\n1n * 2\n// ↪ TypeError: Cannot mix BigInt and other types, use explicit conversions\n\n```\n\n`BigInt`s also cannot be converted to `Number`s using the unary `+`. `Number` must be used.\n\n```js\n\n+1n\n// ↪ TypeError: Cannot convert a BigInt value to a number\n\nNumber(1n)\n// ↪ 1\n\n```\n\nThe `BigInt` *can* however be concatenated with a `String`.\n\n\n```js\n\n1n + '2'\n// ↪ \"12\"\n\n'2' + 1n\n// ↪ \"21\"\n\n```\n\nFor this reason, it is recommended to continue using `Number` for code which will only encounter values under 2\u003csup\u003e53\u003c/sup\u003e.\n\nReserve `BigInt` for cases where large values are expected. Otherwise, by converting back and forth, you may lose the very precision you are hoping to preserve.\n\n```js\nconst largeFriend = 900719925474099267n;\nconst alsoLarge = largeFriend + 2n;\n\nconst sendMeTheBiggest = (n, m) =\u003e Math.max(Number(n), Number(m));\n\nsendMeTheBiggest(largeFriend, alsoLarge)\n// ↪900719925474099300  // This is neither argument!\n```\n\nReserve `Number` values for cases when they are integers up to 2\u003csup\u003e53\u003c/sup\u003e, for other cases, using a string (or a `BigInt` literal) would be advisable to not lose precision.\n\n```js\nconst badPrecision = BigInt(9007199254740993);\n// ↪9007199254740992n\n\nconst goodPrecision = BigInt('9007199254740993');\n// ↪9007199254740993n\n\nconst alsoGoodPrecision = 9007199254740993n;\n// ↪9007199254740993n\n```\n\n### Rounding\n\nAs noted above, the `BigInt` only represents whole numbers. `Number` only reliably represents integers up to 2\u003csup\u003e53\u003c/sup\u003e. That means both dividing and converting to a `Number` can lead to rounding.\n\n```js\n\n5n / 2n\n// ↪ 2n\n\nNumber(151851850485185185047n)\n// ↪ 151851850485185200000\n\n```\n\n### Cryptography\n\nThe operations supported on `BigInt`s are not constant time.  `BigInt` is therefore [unsuitable for use in cryptography](https://www.chosenplaintext.ca/articles/beginners-guide-constant-time-cryptography.html).\n\nMany platforms provide native support for cryptography, such as [webcrypto](https://w3c.github.io/webcrypto/Overview.html) or [node crypto](https://nodejs.org/dist/latest/docs/api/crypto.html).\n\n\n### Other Exceptions\n\nAttempting to convert a fractional value to a `BigInt` throws an exception both when the value is represented as an `Number` and a `String`.\n\n```js\nBigInt(1.5)\n// ↪ RangeError: The number 1.5 is not a safe integer and thus cannot be converted to a BigInt\n\nBigInt('1.5')\n// ↪ SyntaxError: Cannot convert 1.5 to a BigInt\n\n```\n\nOperations in the `Math` library will throw an error when used with `BigInt`s, as will `|`.\n\n```js\n\nMath.round(1n)\n// ↪ TypeError: Cannot convert a BigInt value to a number\n\nMath.max(1n, 10n)\n// ↪ TypeError: Cannot convert a BigInt value to a number\n\n1n|0\n// ↪ TypeError: Cannot mix BigInt and other types, use explicit conversions\n\n```\n\n`parseInt` and `parseFloat` will however convert a `BigInt` to a  `Number` and lose precision in the process. (This is because these functions discard trailing non-numeric values — including `n`.\n\n```js\n\nparseFloat(1234n)\n// ↪1234\n\nparseInt(10n)\n// ↪10\n\n// precision lost!\nparseInt(900719925474099267n)\n// ↪900719925474099300\n```\n\nFinally, `BigInt`s cannot be serialized to JSON. There are, however, libraries — for instance, [granola](https://github.com/kanongil/granola) — that can handle this for you.\n\n```js\nconst bigObj = {a: BigInt(10n)};\nJSON.stringify(bigObj)\n// ↪TypeError: Do not know how to serialize a BigInt\n```\n\n### Usage Recommendations\n\n### Coercion\nBecause coercing between `Number` and BigInt can lead to loss of precision, it is recommended to only use BigInt when values greater than 2\u003csup\u003e53\u003c/sup\u003e are reasonably expected and not to coerce between the two types.\n\n## About the Proposal\n\n### Motivation: Why Do We Need Such Big Numbers?\n\nThere are a number of cases in JavaScript coding where integers larger than 2\u003csup\u003e53\u003c/sup\u003e come up — both instances where signed or unsigned 64-bit integers are needed and times where we may want integers even larger than 64-bits.\n\n#### 64-bit Use Cases\n\nOften, other systems with which Javascript interacts provides data as 64-bit integers, which lose precision when coerced to Javascript Numbers.\n\nThese might come when reading certain machine registers or wire protocols or using protobufs or JSON documents that have GUIDs generated by 64-bit systems in them — including things like credit card or account numbers — which currently must remain strings in Javascript. (Note, however, `BigInt`s cannot be serialized to JSON directly. But you can use libraries like [granola](https://github.com/kanongil/granola) to serialize and deserialize BigInt and other JS datatypes to JSON.)\n\nIn node, `fs.stat` may give some data as 64-bit integers, which [has caused issues already](https://github.com/nodejs/node/issues/12115):\n\n```js\nfs.lstatSync('one.gif').ino\n// ↪ 9851624185071828\n\nfs.lstatSync('two.gif').ino\n// ↪ 9851624185071828, duplicate, but different file!\n```\n\nFinally, 64-bit integers enable higher resolution — _nanosecond!_ — timestamps. These will be put to use in the [temporal proposal](https://github.com/tc39/proposal-temporal), currently in Stage 1.\n\n#### Bigger Than 64-bit Use Cases\n\nIntegers larger than 64-bit values are most likely to arise when  doing mathematical calculations with larger integers, such as solving Project Euler problems or exact geometric calculations. Adding `BigInt` makes it possible to meet a reasonable user expectation of a high-level language that integer arithmetic will be \"correct\" and not suddenly overflow.\n\nIf this seems far-fetched, consider the case of [the Pentium FDIV bug](https://en.wikipedia.org/wiki/Pentium_FDIV_bug). In 1994, a bug in Pentium chips made floating point values rarely —but possibly — imprecise. It was discovered by a mathematics professor who was relying on that precision. \n\n### Design Goals, Or Why Is This Like This?\n\nThese principles guided the decisions made with this proposal. Check out [`ADVANCED.md`](/ADVANCED.md) for more in-depth discussion of each.\n\n#### Find a balance between maintaining user intuition and preserving precision\n\nIn general, this proposal has aimed to work in a manner complementary to user intuition about how Javascript works. At the same time, the goal for this proposal is to add further affordances for precision to the language. Sometimes these can conflict.\n\nWhen a messy situation comes up, this proposal errs on the side of throwing an exception rather than rely on type coercion and risk giving an imprecise answer. This is what's behind throwing a `TypeError` on adding a `BigInt` and a `Number` and other [exceptions detailed above](#gotchas--exceptions): If we don't have a good answer, better to not give one.\n\nFor more discussion of these choices, see [Axel Rauschmeyer's proposal](https://gist.github.com/rauschma/13d48d1c49615ce2396ce7c9e45d4cd1) and [further discussion of its effects on Numbers](https://github.com/tc39/proposal-integer/issues/36). We ended up concluding that it would be impractical to provide transparent interoperability between Number and BigInt.\n\n#### Don't break math\n\nThe semantics of all operators should ideally be based on some mathematical first principles, to match developer expectations. The division and modulo operators are based on conventions from other programming languages for integers.\n\n#### Don't break JavaScript ergonomics\n\nThis proposal comes with built-in operator overloading in order to not make `BigInt`s too ugly to be usable. One particular hazard, if `BigInts` were to be operated on with static methods, is that users may convert the `BigInt` into a `Number` in order to use the `+` operator on it--this would work most of the time, just not with big enough values, so it might pass tests. By including operator overloading, it would be even shorter code to add the `BigInt`s properly than to convert them to `Numbers`, which minimizes the chance of this bug.\n\n#### Don't break the web\n\nThis proposal doesn't change anything about the way Numbers work. The name `BigInt` was chosen in part to avoid compatibility risks carried by the more general `Integer` name (and in part to make it clear that they are useful for the \"big\" cases).\n\n#### Don't break good performance\n\nDesign work here has been done in conjunction with prototyping in to ensure that the proposal is efficiently implementable.\n\n#### Don't break potential future value types extensions\n\nWhen adding new primitives to the language, it is important to avoid giving them superpowers that would be very difficult to generalize. This is another good reason for `BigInt` to avoid mixed operands.\n\nMixed comparisons are a one-off exception to this principle, however, taken in support of the intuition design principle.\n\n#### Don't break a consistent model of JavaScript\n\nThis proposal adds a new primitive type with wrappers, similar to `Symbol`. As part of integrating `BigInt`s into the JavaScript specification, a high amount of rigor will be required to differentiate three types floating around in the specification: Mathematical values, `BigInt`s and `Number`s.\n\n### State of the Proposal\n\nThis proposal is currently in [Stage 4.](https://tc39.github.io/process-document/)\n\n`BigInt` has been shipped in Chrome, Node, Firefox, and is underway in Safari.\n- [V8](https://bugs.chromium.org/p/v8/issues/detail?id=6791) by Georg Neis and Jakob Kummerow.\n- [JSC](https://bugs.webkit.org/show_bug.cgi?id=179001) by Caio Lima and Robin Morisset.\n- [SpiderMonkey](https://bugzilla.mozilla.org/show_bug.cgi?id=1366287) by Robin Templeton and Andy Wingo.\n\nRelated specification proposals:\n- [BigInt WebAssembly JS API integration proposal](https://github.com/WebAssembly/spec/pull/707)\t\n- [HTML serialization of BigInt](https://github.com/whatwg/html/pull/3480)\t\n- [BigInt as an IndexedDB key](https://github.com/w3c/IndexedDB/pull/231)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftc39%2Fproposal-bigint","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftc39%2Fproposal-bigint","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftc39%2Fproposal-bigint/lists"}