JavaScript BigInt
JavaScript BigInt variables are used to store big integer values
that are too big to be represented by a normal JavaScript Number.
JavaScript Integer Accuracy
JavaScript integers are only accurate up to 15 digits:
In JavaScript, all numbers are stored in a 64-bit floating-point format (IEEE 754 standard).
With this standard, large integer cannot be exactly represented and will be rounded.
Because of this, JavaScript can only safely represent integers:
Up to 9007199254740991 +(253-1)
and
Down to -9007199254740991 -(253-1).
Integer values outside this range lose precision.
How to Create a BigInt
To create a BigInt, append n to the end of an integer
OR call BigInt():
Examples
let y = BigInt("999999999999999");
let y = BigInt("1234567890123456789012345")
BigInt: A new JavaScript Datatype
The JavaScript typeof a BigInt is "bigint":
BigInt is the second numeric data type in JavaScript
(after Number).
With BigInt the total number of supported data types in JavaScript is 8:
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object
BigInt Operators
Operators that can be used on a JavaScript Number
can also be used on a BigInt.
BigInt Multiplication Example
let y = 9007199254740995n;
let z = x * y;
Notes
Arithmetic between a BigInt
and a Number is not allowed (type conversion lose information).
Unsigned right shift (>>>) can not be done on a BigInt
(it does not have a fixed width).
BigInt Decimals
A BigInt can not have decimals.
BigInt Division Example
let y = x / 2;
// Error: Cannot mix BigInt and other types, use explicit conversion.
let y = Number(x) / 2;
BigInt Hex, Octal and Binary
BigInt can also be written in hexadecimal, octal, or binary notation:
Like numbers, bigint literals support several bases:
- Normal: 256n
- Octal: 0o400n
- Hexadecimal: 0x100n
- Binary: 0b100000000n
Examples
let oct = 0o400n;
let hex = 0x100n;
let bin = 0b100000000n;
let oct = 0o400000000000000003n;
let bin = 0b100000000000000000000000000000000000000000000000000011n;
Precision Curiosity
Maximum safe integer in JavaScript is 9007199254740991.
Rounding can compromise program security:
MAX_SAFE_INTEGER Examples
Browser Support
BigInt() is an ES2020 feature.
ES2020 is fully supported in all modern browsers since September 2020:
| Chrome 85 |
Edge 85 |
Firefox 79 |
Safari 14 |
Opera 71 |
| Aug 2020 | Aug 2020 | Mar 2020 | Sep 2020 | Sep 2020 |