InterviewHubPRO
Section Overview
Q484

Question 484 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

93%
JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

What is BigInt and how is it different from Number?

BigInt is a built-in JavaScript object (introduced in ES2020) that provides a way to represent whole numbers larger than 2^53 - 1 (the largest number JavaScript can reliably represent with the Number primitive).

Key Differences:

FeatureNumberBigInt
Maximum Safe Integer2^53 - 1 (9,007,199,254,740,991)No theoretical limit
Syntax4242n or BigInt(42)
Type"number""bigint"
DecimalsSupports decimalsInteger only
Math OperationsWorks with Math objectCannot use Math object
JSONNative JSON supportNo native JSON support
Mixing OperationsN/ACannot mix with Number without explicit conversion

Creating BigInt:

javascript
 // Using 'n' suffix
 const bigInt1 = 9007199254740991n;
 const bigInt2 = 123456789012345678901234567890n;

 // Using BigInt() function
 const bigInt3 = BigInt("9007199254740991");
 const bigInt4 = BigInt(9007199254740991);

 console.log(typeof bigInt1); // "bigint"

Common Use Cases:

javascript
 // 1. Large integer arithmetic
 const largeNumber = 9007199254740992n;
 const result = largeNumber + 1n; // 9007199254740993n

 // Problem with Number:
 console.log(9007199254740992 + 1); // 9007199254740992 (incorrect!)
 console.log(9007199254740992n + 1n); // 9007199254740993n (correct!)

 // 2. High-precision calculations
 const factorial = (n) => {
   if (n === 0n) return 1n;
   return n * factorial(n - 1n);
 };
 console.log(factorial(50n)); // Accurate result for 50!

 // 3. Cryptography and unique identifiers
 const uniqueId = 1234567890123456789012345n;

 // Important: Cannot mix BigInt and Number
 const num = 10;
 const big = 20n;
 // console.log(num + big); // TypeError: Cannot mix BigInt and other types
 console.log(BigInt(num) + big); // 30n (correct)
 console.log(num + Number(big)); // 30 (correct, but loses precision for large values)

 // Comparison works across types
 console.log(10n == 10);  // true
 console.log(10n === 10); // false (different types)
 console.log(10n < 15);   // true

Limitations:

javascript
 // No decimal support
 const decimal = 3.5n; // SyntaxError

 // Cannot use with Math object
 Math.sqrt(16n); // TypeError

 // JSON serialization requires custom handling
 const data = { id: 123n };
 JSON.stringify(data); // TypeError: Do not know how to serialize a BigInt

 // Solution for JSON:
 JSON.stringify(data, (key, value) => 
   typeof value === 'bigint' ? value.toString() : value
 );