← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 11 of 12

JS BigInt

Regular JavaScript numbers are like a calculator display with a fixed number of digits; once a whole number gets big enough, it starts losing precision because it runs out of room. BigInt is a second numeric type that grows its digit tape as needed, letting you represent integers of essentially unlimited size, which regular numbers simply can't do accurately.

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

javascript
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

javascript
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

javascript
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

javascript
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

javascript
// 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);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.