I volontari di MDN non hanno ancora tradotto questo articolo in Italiano. Unisciti a noi e traducilo tu stesso.
Puoi anche consultare l’articolo in English (US).

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

BigInt is a built-in object that provides a way to represent whole numbers larger than 253, which is the largest number JavaScript can reliably represent with the Number primitive.

Syntax

BigInt(value);

Parameters

value
The numeric value of the object being created. May be a string or an integer.

Note: BigInt() is not used with the new operator.

Description

A BigInt is created by appending n to the end of an integer literal — 10n — or by calling the function BigInt().

const theBiggestInt = 9007199254740991n;

const alsoHuge = BigInt(9007199254740991);
// ↪ 9007199254740991n

const hugeString = BigInt("9007199254740991");
// ↪ 9007199254740991n

const hugeHex = BigInt("0x1fffffffffffff");
// ↪ 9007199254740991n

const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
// ↪ 9007199254740991n

It is similar to a Number in some ways, but also differs in a few key matters — it cannot be used with methods in the built-in Math object and cannot be mixed in operations with any instances of Number.

Number and BigInt cannot be mixed in operations — they must be coerced to the same type.

Be careful coercing values back and forth, however, as the precision of a BigInt may be lost when it is coerced to a Number.

Type information

When tested against typeof, a BigInt will give "bigint":

typeof 1n === 'bigint'; // true
typeof BigInt('1') === 'bigint'; // true

When wrapped in an Object, a BigInt will be considered as a normal "object" type:

typeof Object(1n) === 'object'; // true

Operators

The following operators may be used with BigInts (or object-wrapped BigInts): +, *, -, **, %.

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

An operation with a fractional result will be truncated when used with a BigInt.

const expected = 4n / 2n;
// ↪ 2n

const rounded = 5n / 2n;
// ↪ 2n, not 2.5n

Comparisons

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

0n === 0
// ↪ false

0n == 0
// ↪ true

A Number and BigInt 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]

Note that comparisons with Object-wrapped BigInts act as with other objects, only indicating equality when the same object instance is compared:

0n === Object(0n); // false
Object(0n) === Object(0n); // false

const o = Object(0n);
o === o // true

Conditionals

A BigInt behaves like a Number in cases where it is converted to a Boolean: via the Boolean function; when used with logical operators Logical Operators ||, &&, and !; or within a conditional test like an if statement.

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

Methods

BigInt.asIntN()
Wraps a BigInt between -2width-1 and 2width-1-1
BigInt.asUintN()
Wraps a BigInt between 0 and 2width-1

Properties

BigInt.prototype
Allows the addition of properties to a BigInt object.

BigInt instances

All BigInt instances inherit from BigInt.prototype. The prototype object of the BigInt constructor can be modified to affect all BigInt instances.

Methods

BigInt.prototype.toLocaleString()
Returns a string with a language sensitive representation of this number. Overrides the Object.prototype.toLocaleString() method.
BigInt.prototype.toString()
Returns a string representing the specified object in the specified radix (base). Overrides the Object.prototype.toString() method.
BigInt.prototype.valueOf()
Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf() method.

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.

Cryptography

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

Examples

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;
}

nthPrime(20n)
// ↪ 73n

Specifications

Specification Status
BigInt Stage 3

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
BigInt
Experimental
Chrome Full support 67Edge No support NoFirefox Full support 68IE No support NoOpera Full support 54Safari No support NoWebView Android Full support 67Chrome Android Full support 67Edge Mobile ? Firefox Android Full support 68Opera Android Full support 48Safari iOS No support NoSamsung Internet Android No support Nonodejs Full support 10.4.0

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.

See also

Tag del documento e collaboratori

Hanno collaborato alla realizzazione di questa pagina: alattalatta, t1anchen, ExE-Boss, mdnwebdocs-bot, fscholz, VFDan, fardelian, Sheppy, sarahgp, coolaj86, Brettz9
Ultima modifica di: alattalatta,