JS BigInt
In this page:
What Is BigInt
BigInt is a built-in numeric type for representing integers of arbitrary size, beyond the precision limits of the regular Number type. You write a BigInt literal by appending the letter n to the end of an integer, such as 123n, which tells JavaScript to treat it as an exact, unlimited-size whole number rather than a floating-point Number.
Example: What Is BigInt
const big = 123n;
console.log(typeof big, big);
Creating BigInt Values
You can create a BigInt either with the n-suffixed literal syntax or by calling the BigInt() function on a number or numeric string. The function form is useful when you need to convert a value that's already stored as a regular Number or string into a BigInt at runtime.
Example: Creating BigInt Values
const a = 123n;
const b = BigInt(456);
const c = BigInt("789");
console.log(a, b, c);
BigInt Arithmetic
BigInt supports the standard arithmetic operators +, -, *, and /, but division always truncates toward zero and discards any remainder, since BigInt has no concept of a fractional part. This means 7n / 2n evaluates to 3n, not 3.5, which can surprise anyone expecting decimal division.
Example: BigInt Arithmetic
console.log(7n / 2n); // 3n, truncated toward zero, not 3.5
Mixing BigInt and Number
JavaScript deliberately throws a TypeError if you try to use arithmetic operators directly between a BigInt and a regular Number, since implicitly converting between the two could silently lose precision either way. You must explicitly convert one side using BigInt() or Number() before combining them.
Example: Mixing BigInt and Number
try {
console.log(5n + 5); // TypeError
} catch (e) {
console.log(e.message);
}
console.log(5n + BigInt(5)); // works after explicit conversion
When to Use BigInt
BigInt is the right tool when a program needs exact integer arithmetic beyond about 9 quadrillion, such as cryptographic key calculations, high-precision timestamps, or unique identifiers imported from systems that use 64-bit integers. For everyday counting and math, regular Numbers remain simpler and faster.
Example: When to Use BigInt
// Use BigInt for exact integers beyond ~9 quadrillion:
const id = 9007199254740993n;
console.log(id);
// Regular numbers are simpler for everyday counting:
const count = 5;
console.log(count);
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: