JavaScript BigInt
Subject: JavaScript
BigInt is a built-in JavaScript data type designed to handle integers larger than the safe limit of the Number type (which is 2⁵³ - 1). Introduced in ECMAScript 2020, BigInt solves issues with precision when dealing with very large integers.
Why Use BigInt?
JavaScript's Number type safely represents integers only between:
- Number.MIN_SAFE_INTEGER (-9007199254740991)
- Number.MAX_SAFE_INTEGER (9007199254740991)
For calculations involving integers outside this range—such as cryptography, scientific computations, or precise financial data—BigInt is necessary.
Creating a BigInt
There are two ways to create a BigInt:
- Using the
nsuffix:
- Using the BigInt constructor:
BigInt vs Number
BigInt Arithmetic
You can use arithmetic operators with BigInt:
Important Rules
- You cannot mix BigInt and Number types directly in arithmetic:
- BigInt does not support decimals. Division truncates the result:
- Use
typeofto check for BigInt:
Use Cases of BigInt
- Cryptography and hashing
- Handling large financial values
- Working with 64-bit integers from databases or APIs
- Blockchain and high-precision timestamps
Key Takeaways
- BigInt enables safe manipulation of integers beyond Number's safe range.
- Create BigInt values with
nsuffix orBigInt()constructor. - Mixing BigInt with Number in expressions requires explicit conversion.
- No decimal support; division results are truncated.
- Ideal for high-precision integer arithmetic scenarios.