What is BigInt in JavaScript: Explanation and Usage
BigInt in JavaScript is a special number type that lets you work with whole numbers larger than Number.MAX_SAFE_INTEGER. It allows you to safely store and operate on very large integers without losing precision.How It Works
JavaScript normally uses the Number type to represent numbers, but it can only safely handle integers up to about 9 quadrillion (253 - 1). Beyond this, numbers lose accuracy, like a ruler that can't measure very long distances precisely.
BigInt solves this by storing numbers as a special type that can grow as large as needed, like using a tape measure instead of a ruler. This means you can do math with huge integers exactly, without rounding errors.
To create a BigInt, you add n at the end of an integer or use the BigInt() function. Operations like addition and multiplication work similarly but only between BigInt values.
Example
This example shows how to create and add two BigInt numbers safely beyond the normal number limit.
const big1 = 9007199254740991n; // Number.MAX_SAFE_INTEGER const big2 = 10n; const sum = big1 + big2; console.log(sum);
When to Use
Use BigInt when you need to work with very large whole numbers that exceed JavaScript's safe integer limit, such as in cryptography, financial calculations, or dealing with large IDs.
For example, if you are handling blockchain data, astronomical calculations, or precise money amounts in cents that can grow very large, BigInt ensures accuracy without rounding errors.
Key Points
BigIntstores integers larger thanNumber.MAX_SAFE_INTEGER.- Use
nsuffix orBigInt()to createBigIntvalues. - Cannot mix
BigIntandNumbertypes in operations without conversion. - Useful for cryptography, finance, and large ID handling.