BigInt is a primitive numerical type introduced in ES2020 that can represent integers of arbitrary magnitude beyond Number.MAX_SAFE_INTEGER ($2^{53} - 1$).
flowchart LR
BigIntType["BigInt Primitive (Suffix 'n')"] --> Limit1["No Upper Safety Boundary"]
NumberType["Number Primitive (64-Bit Float)"] --> Limit2["Safe up to 9,007,199,254,740,991"]
| Feature | Standard Number |
BigInt |
|---|---|---|
| Literal Syntax | 42 |
42n or BigInt(42) |
| Max Safe Limit | $2^{53} - 1$ | Unlimited (bounded only by host memory) |
| Decimal Fractions | Supported (42.5) |
Not Supported (Truncates decimal part) |
| Type Coercion | Interoperable with floats | Cannot mix directly with standard numbers without explicit cast |
// Demonstrating BigInt creation, arithmetic, and mixing restrictions
// 1. Creating BigInt Values
const hugeInt1 = 9007199254740995n; // Append 'n' suffix
const hugeInt2 = BigInt("900719925474099999999999999");
console.log(`BigInt 1: ${hugeInt1}`);
console.log(`Typeof hugeInt1: ${typeof hugeInt1}`); // "bigint"
// 2. BigInt Arithmetic
const sum = hugeInt1 + 10n;
const product = hugeInt1 * 2n;
console.log(`BigInt Sum: ${sum}`);
console.log(`BigInt Product: ${product}`);
// 3. Division Truncation (No decimals)
const divResult = 7n / 2n;
console.log(`BigInt 7n / 2n: ${divResult}`); // 3n (Fractional part dropped!)
// 4. Mixing Restriction Pitfall & Solution
const standardNum = 100;
// const invalidSum = hugeInt1 + standardNum; // Throws TypeError: Cannot mix BigInt and other types
const validSum = hugeInt1 + BigInt(standardNum); // Explicit conversion required
console.log(`Safely mixed sum: ${validSum}`);
BigInt truncates division fractional parts, scale values to cents or smallest currency units before dividing.JSON.stringify() throws a TypeError on objects containing BigInt unless a custom replacer function or toJSON prototype method is provided.===): 42n === 42 returns false because they are different primitive types. Loose equality 42n == 42 returns true.Write a function serializeBigInt(key, value) for JSON.stringify() that converts BigInt values to string representation with an "n" suffix.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.