BigInt
é um objeto nativo que fornece um modo de representar números inteiros maiores que 253, que é o maior número que o JavaScript consegue, com exatidão, representar com o tipo primitivo Number
.
Sintaxe
BigInt(value);
Parâmetros
value
- O valor numérico do objeto que está sendo criado. Pode ser uma string ou um número inteiro.
Observação: BigInt()
não é usado com o operador new
.
Descrição
Um BigInt
é criado com a acrescentação de n
ao final de um inteiro literal — 10n
— ou chamando a função BigInt()
.
const theBiggestInt = 9007199254740991n;
const alsoHuge = BigInt(9007199254740991);
// ↪ 9007199254740991n
const hugeString = BigInt("9007199254740991");
// ↪ 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff");
// ↪ 9007199254740991n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
// ↪ 9007199254740991n
Isso é parecido com um Number
em algumas partes, mas difere-se em alguns assuntos importantes — ele não pode ser usado com métodos no objeto Math
e não pode ser misturado em operações ou qualquer instância de Number
.
Number
e BigInt
não podem ser misturados em operações — eles devem ser manipulados com o mesmo tipo.
Tenha cuidado com a conversão e desconversão de valores, visto que a precisão de BigInt
pode ser perdida com a conversào para Number
.
Informações do tipo
Quando testado com typeof
, um BigInt
vai devolver "bigint":
typeof 1n === 'bigint'; // true
typeof BigInt('1') === 'bigint'; // true
Quando envolvido em um Object
, um BigInt
vai ser considerado como um tipo normal de "object".
typeof Object(1n) === 'object'; // true
Operadores
Os seguintes operadores podem ser usados com BigInt
s (ou com BigInt
s envolvidos em objetos): +
, `*
`, `-
`, `**
`, `%
` .
const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);
// ↪ 9007199254740991
const maxPlusOne = previousMaxSafe + 1n;
// ↪ 9007199254740992n
const theFuture = previousMaxSafe + 2n;
// ↪ 9007199254740993n, isso funciona agora!
const multi = previousMaxSafe * 2n;
// ↪ 18014398509481982n
const subtr = multi – 10n;
// ↪ 18014398509481972n
const mod = multi % 10n;
// ↪ 2n
const bigN = 2n ** 54n;
// ↪ 18014398509481984n
bigN * -1n
// ↪ –18014398509481984n
O operador /
também funciona com o esperado com números inteiros. No entanto, desde que esses sejam BigInt
s e não BigDecimal
s, essa operação vai arredondar para 0, o que significa que não vai retornar qualquer valor fracional.
Uma operação com um resultado fracional será arredondado com BigInt.
const expected = 4n / 2n;
// ↪ 2n
const rounded = 5n / 2n;
// ↪ 2n, e não 2.5n
Comparações
Um BigInt
não é estritamente igual a um Number
, mas é mais ou menos assim.
0n === 0
// ↪ false
0n == 0
// ↪ true
Um Number
e um BigInt
podem ser comparado normalmente.
1n < 2
// ↪ true
2n > 1
// ↪ true
2 > 2
// ↪ false
2n > 2
// ↪ false
2n >= 2
// ↪ true
Eles podem ser misturados em arrays e sorteados.
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]
Observe que comparações com BigInt
s envolvidos em Object
atuam com outros objetos, indicando somente a igualdade onde a mesma instância do objeto é comparada.
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.
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