• This repository has been archived on 10/Oct/2019
  • Stars
    star
    560
  • Rank 76,415 (Top 2 %)
  • Language
    HTML
  • Created about 7 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Arbitrary precision integers in JavaScript

BigInt: Arbitrary precision integers in JavaScript

Daniel Ehrenberg, Igalia. Stage 4

This proposal is complete and already merged into ECMA262 specification. See the specification text here.

Thanks 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.

Contents

  1. What Is It?
  2. How Does It Work?
  3. Gotchas & Exceptions
  4. About the Proposal

What Is It?

BigInt is a new primitive that provides a way to represent whole numbers larger than 253, which is the largest number Javascript can reliably represent with the Number primitive.

const x = Number.MAX_SAFE_INTEGER;
// β†ͺ 9007199254740991, this is 1 less than 2^53

const y = x + 1;
// β†ͺ 9007199254740992, ok, checks out

const z = x + 2
// β†ͺ 9007199254740992, wait, that’s the same as above!

Learn more about how numbers are represented in Javascript in the slides from Daniel's talk at JSConfEU.

How Does It Work?

The 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.

Syntax

A BigInt is created by appending n to the end of the integer or by calling the constructor.

const theBiggestInt = 9007199254740991n;

const alsoHuge = BigInt(9007199254740991);
// β†ͺ 9007199254740991n

const hugeButString = BigInt('9007199254740991');
// β†ͺ 9007199254740991n

Example: Calculating Primes

function isPrime(p) {
  for (let i = 2n; i * i <= p; i++) {
    if (p % i === 0n) return false;
  }
  return true;
}

// Takes a BigInt as an argument and returns a BigInt
function nthPrime(nth) {
  let maybePrime = 2n;
  let prime = 0n;
  
  while (nth >= 0n) {
    if (isPrime(maybePrime)) {
      nth -= 1n;
      prime = maybePrime;
    }
    maybePrime += 1n;
  }
  
  return prime;
}

Operators

You can use +, *, -, ** and % with BigInts, just like with Numbers.

const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);
// β†ͺ 9007199254740991

const maxPlusOne = previousMaxSafe + 1n;
// β†ͺ 9007199254740992n
 
const theFuture = previousMaxSafe + 2n;
// β†ͺ 9007199254740993n, this works now!

const multi = previousMaxSafe * 2n;
// β†ͺ 18014398509481982n

const subtr = multi – 10n;
// β†ͺ 18014398509481972n

const mod = multi % 10n;
// β†ͺ 2n

const bigN = 2n ** 54n;
// β†ͺ 18014398509481984n

bigN * -1n
// β†ͺ –18014398509481984n

The / operator also work as expected with whole numbers. However, since these are BigInts and not BigDecimals, this operation will round towards 0, which is to say, it will not return any fractional digits.

const expected = 4n / 2n;
// β†ͺ 2n

const rounded = 5n / 2n;
// β†ͺ 2n, not 2.5n

See the advanced documentation for use with bitwise operators.

Comparisons

A BigInt is not strictly equal to a Number, but it is loosely so.

0n === 0
// β†ͺ false

0n == 0
// β†ͺ true

Numbers and BigInts may be compared as usual.

1n < 2
// β†ͺ true

2n > 1
// β†ͺ true

2 > 2
// β†ͺ false

2n > 2
// β†ͺ false

2n >= 2
// β†ͺ true

They may be mixed in arrays and sorted.

const mixed = [4n, 6, -12n, 10, 4, 0, 0n];
// β†ͺ Β [4n, 6, -12n, 10, 4, 0, 0n]

mixed.sort();
// β†ͺ [-12n, 0, 0n, 10, 4n, 4, 6]

Conditionals

A BigInt behaves like a Number in cases where it is converted to a Boolean: if, ||, &&, Boolean, !.

if (0n) {
  console.log('Hello from the if!');
} else {
  console.log('Hello from the else!');
}

// β†ͺ "Hello from the else!"

0n || 12n
// β†ͺ 12n

0n && 12n
// β†ͺ 0n

Boolean(0n)
// β†ͺ false

Boolean(12n)
// β†ͺ true

!12n
// β†ͺ false

!0n
// β†ͺ true

Other API Notes

BigInts may also be used in BigInt64Array and BigUint64Array typed arrays for 64-bit integers.

const view = new BigInt64Array(4);
// β†ͺ [0n, 0n, 0n, 0n]
view.length;
// β†ͺ 4
view[0];
// β†ͺ 0n
view[0] = 42n;
view[0];
// β†ͺ 42n

// Highest possible BigInt value that can be represented as a
// signed 64-bit integer.
const max = 2n ** (64n - 1n) - 1n;
view[0] = max;
view[0];
// β†ͺ 9_223_372_036_854_775_807n
view[0] = max + 1n;
view[0];
// β†ͺ -9_223_372_036_854_775_808n
//   ^ negative because of overflow

For more about BigInt library functions, see the advanced section.

Gotchas & Exceptions

Interoperation with Number and String

The biggest surprise may be that BigInts cannot be operated on interchangeably with Numbers. Instead a TypeError will be thrown. (Read the design philosophy for more about why this decision was made.)

1n + 2
// β†ͺ TypeError: Cannot mix BigInt and other types, use explicit conversions

1n * 2
// β†ͺ TypeError: Cannot mix BigInt and other types, use explicit conversions

BigInts also cannot be converted to Numbers using the unary +. Number must be used.

+1n
// β†ͺ TypeError: Cannot convert a BigInt value to a number

Number(1n)
// β†ͺ 1

The BigInt can however be concatenated with a String.

1n + '2'
// β†ͺ "12"

'2' + 1n
// β†ͺ "21"

For this reason, it is recommended to continue using Number for code which will only encounter values under 253.

Reserve 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.

const largeFriend = 900719925474099267n;
const alsoLarge = largeFriend + 2n;

const sendMeTheBiggest = (n, m) => Math.max(Number(n), Number(m));

sendMeTheBiggest(largeFriend, alsoLarge)
// β†ͺ900719925474099300  // This is neither argument!

Reserve Number values for cases when they are integers up to 253, for other cases, using a string (or a BigInt literal) would be advisable to not lose precision.

const badPrecision = BigInt(9007199254740993);
// β†ͺ9007199254740992n

const goodPrecision = BigInt('9007199254740993');
// β†ͺ9007199254740993n

const alsoGoodPrecision = 9007199254740993n;
// β†ͺ9007199254740993n

Rounding

As noted above, the BigInt only represents whole numbers. Number only reliably represents integers up to 253. That means both dividing and converting to a Number can lead to rounding.

5n / 2n
// β†ͺ 2n

Number(151851850485185185047n)
// β†ͺ 151851850485185200000

Cryptography

The operations supported on BigInts are not constant time. BigInt is therefore unsuitable for use in cryptography.

Many platforms provide native support for cryptography, such as webcrypto or node crypto.

Other Exceptions

Attempting to convert a fractional value to a BigInt throws an exception both when the value is represented as an Number and a String.

BigInt(1.5)
// β†ͺ RangeError: The number 1.5 is not a safe integer and thus cannot be converted to a BigInt

BigInt('1.5')
// β†ͺ SyntaxError: Cannot convert 1.5 to a BigInt

Operations in the Math library will throw an error when used with BigInts, as will |.

Math.round(1n)
// β†ͺ TypeError: Cannot convert a BigInt value to a number

Math.max(1n, 10n)
// β†ͺ TypeError: Cannot convert a BigInt value to a number

1n|0
// β†ͺ TypeError: Cannot mix BigInt and other types, use explicit conversions

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.

parseFloat(1234n)
// β†ͺ1234

parseInt(10n)
// β†ͺ10

// precision lost!
parseInt(900719925474099267n)
// β†ͺ900719925474099300

Finally, BigInts cannot be serialized to JSON. There are, however, libraries β€” for instance, granola β€” that can handle this for you.

const bigObj = {a: BigInt(10n)};
JSON.stringify(bigObj)
// β†ͺTypeError: Do not know how to serialize a BigInt

Usage Recommendations

Coercion

Because coercing between Number and BigInt can lead to loss of precision, it is recommended to only use BigInt when values greater than 253 are reasonably expected and not to coerce between the two types.

About the Proposal

Motivation: Why Do We Need Such Big Numbers?

There are a number of cases in JavaScript coding where integers larger than 253 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.

64-bit Use Cases

Often, other systems with which Javascript interacts provides data as 64-bit integers, which lose precision when coerced to Javascript Numbers.

These 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, BigInts cannot be serialized to JSON directly. But you can use libraries like granola to serialize and deserialize BigInt and other JS datatypes to JSON.)

In node, fs.stat may give some data as 64-bit integers, which has caused issues already:

fs.lstatSync('one.gif').ino
// β†ͺ 9851624185071828

fs.lstatSync('two.gif').ino
// β†ͺ 9851624185071828, duplicate, but different file!

Finally, 64-bit integers enable higher resolution β€” nanosecond! β€” timestamps. These will be put to use in the temporal proposal, currently in Stage 1.

Bigger Than 64-bit Use Cases

Integers 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.

If this seems far-fetched, consider the case of the 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.

Design Goals, Or Why Is This Like This?

These principles guided the decisions made with this proposal. Check out ADVANCED.md for more in-depth discussion of each.

Find a balance between maintaining user intuition and preserving precision

In 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.

When 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: If we don't have a good answer, better to not give one.

For more discussion of these choices, see Axel Rauschmeyer's proposal and further discussion of its effects on Numbers. We ended up concluding that it would be impractical to provide transparent interoperability between Number and BigInt.

Don't break math

The 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.

Don't break JavaScript ergonomics

This proposal comes with built-in operator overloading in order to not make BigInts 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 BigInts properly than to convert them to Numbers, which minimizes the chance of this bug.

Don't break the web

This 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).

Don't break good performance

Design work here has been done in conjunction with prototyping in to ensure that the proposal is efficiently implementable.

Don't break potential future value types extensions

When 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.

Mixed comparisons are a one-off exception to this principle, however, taken in support of the intuition design principle.

Don't break a consistent model of JavaScript

This proposal adds a new primitive type with wrappers, similar to Symbol. As part of integrating BigInts into the JavaScript specification, a high amount of rigor will be required to differentiate three types floating around in the specification: Mathematical values, BigInts and Numbers.

State of the Proposal

This proposal is currently in Stage 4.

BigInt has been shipped in Chrome, Node, Firefox, and is underway in Safari.

  • V8 by Georg Neis and Jakob Kummerow.
  • JSC by Caio Lima and Robin Morisset.
  • SpiderMonkey by Robin Templeton and Andy Wingo.

Related specification proposals:

More Repositories

1

proposals

Tracking ECMAScript Proposals
17,177
star
2

ecma262

Status, process, and documents for ECMA-262
HTML
14,437
star
3

proposal-pipeline-operator

A proposal for adding a useful pipe operator to JavaScript.
HTML
7,380
star
4

proposal-pattern-matching

Pattern matching syntax for ECMAScript
HTML
5,341
star
5

proposal-optional-chaining

HTML
4,952
star
6

proposal-type-annotations

ECMAScript proposal for type syntax that is erased - Stage 1
JavaScript
4,090
star
7

proposal-temporal

Provides standard objects and functions for working with dates and times.
HTML
3,135
star
8

proposal-observable

Observables for ECMAScript
JavaScript
3,032
star
9

proposal-signals

A proposal to add signals to JavaScript.
TypeScript
2,668
star
10

proposal-decorators

Decorators for ES6 classes
2,640
star
11

proposal-record-tuple

ECMAScript proposal for the Record and Tuple value types. | Stage 2: it will change!
HTML
2,423
star
12

test262

Official ECMAScript Conformance Test Suite
JavaScript
2,073
star
13

proposal-dynamic-import

import() proposal for JavaScript
HTML
1,859
star
14

proposal-bind-operator

This-Binding Syntax for ECMAScript
1,736
star
15

proposal-class-fields

Orthogonally-informed combination of public and private fields proposals
HTML
1,720
star
16

proposal-async-await

Async/await for ECMAScript
HTML
1,577
star
17

proposal-object-rest-spread

Rest/Spread Properties for ECMAScript
HTML
1,496
star
18

proposal-shadowrealm

ECMAScript Proposal, specs, and reference implementation for Realms
HTML
1,365
star
19

proposal-nullish-coalescing

Nullish coalescing proposal x ?? y
HTML
1,233
star
20

proposal-iterator-helpers

Methods for working with iterators in ECMAScript
HTML
1,220
star
21

proposal-top-level-await

top-level `await` proposal for ECMAScript (stage 4)
HTML
1,082
star
22

proposal-partial-application

Proposal to add partial application to ECMAScript
HTML
1,002
star
23

proposal-do-expressions

Proposal for `do` expressions
HTML
990
star
24

agendas

TC39 meeting agendas
JavaScript
952
star
25

proposal-binary-ast

Binary AST proposal for ECMAScript
945
star
26

proposal-built-in-modules

HTML
886
star
27

proposal-async-iteration

Asynchronous iteration for JavaScript
HTML
854
star
28

proposal-explicit-resource-management

ECMAScript Explicit Resource Management
JavaScript
671
star
29

proposal-operator-overloading

JavaScript
610
star
30

proposal-string-dedent

TC39 Proposal to remove common leading indentation from multiline template strings
HTML
588
star
31

proposal-set-methods

Proposal for new Set methods in JS
HTML
557
star
32

proposal-import-attributes

Proposal for syntax to import ES modules with assertions
HTML
538
star
33

ecmascript_simd

SIMD numeric type for EcmaScript
JavaScript
536
star
34

proposal-slice-notation

HTML
515
star
35

proposal-change-array-by-copy

Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change.
HTML
509
star
36

ecma402

Status, process, and documents for ECMA 402
HTML
506
star
37

notes

TC39 meeting notes
JavaScript
496
star
38

proposal-class-public-fields

Stage 2 proposal for public class fields in ECMAScript
HTML
489
star
39

proposal-iterator.range

A proposal for ECMAScript to add a built-in Iterator.range()
HTML
464
star
40

proposal-uuid

UUID proposal for ECMAScript (Stage 1)
JavaScript
462
star
41

proposal-throw-expressions

Proposal for ECMAScript 'throw' expressions
JavaScript
425
star
42

proposal-module-expressions

HTML
424
star
43

proposal-UnambiguousJavaScriptGrammar

413
star
44

proposal-decimal

Built-in decimal datatype in JavaScript
HTML
408
star
45

proposal-array-grouping

A proposal to make grouping of array items easier
HTML
407
star
46

proposal-async-context

Async Context for JavaScript
HTML
406
star
47

proposal-weakrefs

WeakRefs
HTML
404
star
48

proposal-error-cause

TC39 proposal for accumulating errors
HTML
378
star
49

proposal-ecmascript-sharedmem

Shared memory and atomics for ECMAscript
HTML
376
star
50

proposal-cancelable-promises

Former home of the now-withdrawn cancelable promises proposal for JavaScript
Shell
376
star
51

proposal-relative-indexing-method

A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray)
HTML
351
star
52

proposal-first-class-protocols

a proposal to bring protocol-based interfaces to ECMAScript users
350
star
53

proposal-global

ECMAScript Proposal, specs, and reference implementation for `global`
HTML
346
star
54

proposal-private-methods

Private methods and getter/setters for ES6 classes
HTML
344
star
55

proposal-numeric-separator

A proposal to add numeric literal separators in JavaScript.
HTML
327
star
56

proposal-private-fields

A Private Fields Proposal for ECMAScript
HTML
320
star
57

proposal-object-from-entries

TC39 proposal for Object.fromEntries
HTML
317
star
58

proposal-module-declarations

JavaScript Module Declarations
HTML
314
star
59

proposal-promise-allSettled

ECMAScript Proposal, specs, and reference implementation for Promise.allSettled
HTML
314
star
60

tc39.github.io

Get involved in specifying JavaScript
HTML
313
star
61

proposal-regex-escaping

Proposal for investigating RegExp escaping for the ECMAScript standard
JavaScript
309
star
62

proposal-await.ops

Introduce await.all / await.race / await.allSettled / await.any to simplify the usage of Promises
HTML
308
star
63

proposal-logical-assignment

A proposal to combine Logical Operators and Assignment Expressions
HTML
302
star
64

proposal-export-default-from

Proposal to add `export v from "mod";` to ECMAScript.
HTML
297
star
65

proposal-promise-finally

ECMAScript Proposal, specs, and reference implementation for Promise.prototype.finally
HTML
278
star
66

proposal-asset-references

Proposal to ECMAScript to add first-class location references relative to a module
268
star
67

proposal-cancellation

Proposal for a Cancellation API for ECMAScript
HTML
262
star
68

proposal-json-modules

Proposal to import JSON files as modules
HTML
259
star
69

proposal-promise-with-resolvers

HTML
255
star
70

proposal-string-replaceall

ECMAScript proposal: String.prototype.replaceAll
HTML
254
star
71

proposal-export-ns-from

Proposal to add `export * as ns from "mod";` to ECMAScript.
HTML
241
star
72

proposal-ses

Draft proposal for SES (Secure EcmaScript)
HTML
217
star
73

proposal-structs

JavaScript Structs: Fixed Layout Objects
216
star
74

proposal-intl-relative-time

`Intl.RelativeTimeFormat` specification [draft]
HTML
215
star
75

proposal-flatMap

proposal for flatten and flatMap on arrays
HTML
215
star
76

proposal-json-parse-with-source

Proposal for extending JSON.parse to expose input source text.
HTML
204
star
77

ecmarkup

An HTML superset/Markdown subset source format for ECMAScript and related specifications
TypeScript
201
star
78

proposal-promise-any

ECMAScript proposal: Promise.any
HTML
198
star
79

proposal-decorators-previous

Decorators for ECMAScript
HTML
184
star
80

proposal-smart-pipelines

Old archived draft proposal for smart pipelines. Go to the new Hack-pipes proposal at js-choi/proposal-hack-pipes.
HTML
181
star
81

proposal-defer-import-eval

A proposal for introducing a way to defer evaluate of a module
HTML
174
star
82

proposal-array-filtering

A proposal to make filtering arrays easier
HTML
171
star
83

proposal-optional-chaining-assignment

`a?.b = c` proposal
168
star
84

proposal-array-from-async

Draft specification for a proposed Array.fromAsync method in JavaScript.
HTML
167
star
85

proposal-extractors

Extractors for ECMAScript
JavaScript
166
star
86

proposal-upsert

ECMAScript Proposal, specs, and reference implementation for Map.prototype.upsert
HTML
165
star
87

proposal-ptc-syntax

Discussion and specification for an explicit syntactic opt-in for Tail Calls.
HTML
165
star
88

how-we-work

Documentation of how TC39 operates and how to participate
161
star
89

proposal-collection-methods

HTML
160
star
90

proposal-Array.prototype.includes

Spec, tests, reference implementation, and docs for ESnext-track Array.prototype.includes
HTML
157
star
91

proposal-error-stacks

ECMAScript Proposal, specs, and reference implementation for Error.prototype.stack / System.getStack
HTML
156
star
92

proposal-promise-try

ECMAScript Proposal, specs, and reference implementation for Promise.try
HTML
154
star
93

proposal-hashbang

#! for JS
HTML
148
star
94

proposal-resizablearraybuffer

Proposal for resizable array buffers
HTML
145
star
95

proposal-import-meta

import.meta proposal for JavaScript
HTML
145
star
96

proposal-intl-segmenter

Unicode text segmentation for ECMAScript
HTML
145
star
97

proposal-extensions

Extensions proposal for ECMAScript
HTML
143
star
98

proposal-seeded-random

Proposal for an options argument to be added to JS's Math.random() function, and some options to start it with.
HTML
143
star
99

proposal-intl-duration-format

141
star
100

proposal-regexp-unicode-property-escapes

Proposal to add Unicode property escapes `\p{…}` and `\P{…}` to regular expressions in ECMAScript.
HTML
134
star