Path: blob/main/files/en-us/web/javascript/reference/global_objects/bigint/index.md
6529 views
------{{JSRef}}
BigInt values represent numeric values which are too large to be represented by the number {{Glossary("Primitive", "primitive")}}.
Description
A BigInt value, also sometimes just called a BigInt, is a bigint {{Glossary("Primitive", "primitive")}}, created by appending n to the end of an integer literal, or by calling the {{jsxref("Global_Objects/BigInt/BigInt", "BigInt()")}} function (without the new operator) and giving it an integer value or string value.
BigInt values are similar to Number values in some ways, but also differ in a few key matters: A BigInt value cannot be used with methods in the built-in Math object and cannot be mixed with a Number value in operations; they must be coerced to the same type. Be careful coercing values back and forth, however, as the precision of a BigInt value may be lost when it is coerced to a Number value.
Type information
When tested against typeof, a BigInt value (bigint primitive) will give "bigint":
A BigInt value can also be wrapped in an Object:
Operators
The following operators may be used with BigInt values or object-wrapped BigInt values:
Bitwise operators are supported as well, except >>> (zero-fill right shift), as every BigInt value is signed.
Also unsupported is the unary operator (+), in order to not break asm.js.
The / operator also works as expected with whole numbers — but operations with a fractional result will be truncated when used with a BigInt value — they won't return any fractional digits.
Comparisons
A BigInt value is not strictly equal to a Number value, but it is loosely so:
A Number value and a BigInt value may be compared as usual:
BigInt values and Number values may be mixed in arrays and sorted:
Note that comparisons with Object-wrapped BigInt values act as with other objects, only indicating equality when the same object instance is compared:
Conditionals
A BigInt value follows the same conversion rules as Numbers when:
when used with logical operators
||,&&, and!; orwithin a conditional test like an
ifstatement.
Namely, only 0n is falsy; everything else is truthy.
BigInt coercion
Many built-in operations that expect BigInts first coerce their arguments to BigInts. The operation can be summarized as follows:
BigInts are returned as-is.
trueturns into1n;falseturns into0n.Strings are converted by parsing them as if they contain an integer literal. Any parsing failure results in a {{jsxref("SyntaxError")}}. The syntax is a subset of string numeric literals, where decimal points or exponent indicators are not allowed.
Numbers throw a {{jsxref("TypeError")}} to prevent unintended implicit coercion causing loss of precision.
Symbols throw a {{jsxref("TypeError")}}.
Objects are first converted to a primitive by calling their
[@@toPrimitive]()(with"number"as hint),valueOf(), andtoString()methods, in that order. The resulting primitive is then converted to a BigInt.
The best way to achieve nearly the same effect in JavaScript is through the BigInt() function: BigInt(x) uses the same algorithm to convert x, except that Numbers don't throw a {{jsxref("TypeError")}}, but are converted to BigInts if they are integers.
Note that built-in operations expecting BigInts often truncate the BigInt to a fixed width after coercion. This includes {{jsxref("BigInt.asIntN()")}}, {{jsxref("BigInt.asUintN()")}}, and methods of {{jsxref("BigInt64Array")}} and {{jsxref("BigUint64Array")}}.
Constructor
: Creates a new BigInt value.
Static methods
: Clamps a BigInt value to a signed integer value, and returns that value.
: Clamps a BigInt value to an unsigned integer value, and returns that value.
Instance properties
These properties are defined on BigInt.prototype and shared by all BigInt instances.
{{jsxref("Object/constructor", "BigInt.prototype.constructor")}}
: The constructor function that created the instance object. For
BigIntinstances, the initial value is the {{jsxref("BigInt/BigInt", "BigInt")}} constructor.
BigInt.prototype[@@toStringTag]: The initial value of the
@@toStringTagproperty is the string"BigInt". This property is used in {{jsxref("Object.prototype.toString()")}}. However, becauseBigIntalso has its owntoString()method, this property is not used unless you callObject.prototype.toString.call()with a BigInt asthisArg.
Instance methods
BigInt.prototype.toLocaleString(): Returns a string with a language-sensitive representation of this BigInt value. Overrides the
Object.prototype.toLocaleString()method.
: Returns a string representing this BigInt value in the specified radix (base). Overrides the
Object.prototype.toString()method.
: Returns this BigInt value. Overrides the
Object.prototype.valueOf()method.
Usage recommendations
Coercion
Because coercing between Number values and BigInt values can lead to loss of precision, the following are recommended:
Only use a BigInt value when values greater than 2^53 are reasonably expected.
Don't coerce between BigInt values and Number values.
Cryptography
The operations supported on BigInt values are not constant-time and are thus open to timing attacks. JavaScript BigInts therefore could be dangerous for use in cryptography without mitigating factors. As a very generic example, an attacker could measure the time difference between 101n ** 65537n and 17n ** 9999n, and deduce the magnitude of secrets, such as private keys, based on the time elapsed. If you still have to use BigInts, take a look at the Timing attack FAQ for general advice regarding the issue.
Use within JSON
Using JSON.stringify() with any BigInt value will raise a TypeError, as BigInt values aren't serialized in JSON by default. However, JSON.stringify() specifically leaves a backdoor for BigInt values: it would try to call the BigInt's toJSON() method. (It doesn't do so for any other primitive values.) Therefore, you can implement your own toJSON() method (which is one of the few cases where patching built-in objects is not explicitly discouraged):
Instead of throwing, JSON.stringify() now produces a string like this:
If you do not wish to patch BigInt.prototype, you can use the replacer parameter of JSON.stringify to serialize BigInt values:
If you have JSON data containing values you know will be large integers, you can use the reviver parameter of JSON.parse to handle them:
Note: While it's possible to make the replacer of
JSON.stringify()generic and properly serialize BigInt values for all objects, the reviver ofJSON.parse()must be specific to the payload shape you expect, because the serialization is lossy: it's not possible to distinguish between a string that represents a BigInt and a normal string.
Examples
Calculating Primes
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}