Module 37 // Core JavaScript

BigInt

Module Objective

BigInt literals, arithmetic, interoperability limits

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. Precise Large Numbers
const maxSafe = Number.MAX_SAFE_INTEGER; // 9007199254740991

console.log(maxSafe + 1); // 9007199254740992
console.log(maxSafe + 2); // 9007199254740992 (Incorrect!)

const big = BigInt(maxSafe);
console.log(big + 1n); // 9007199254740992n
console.log(big + 2n); // 9007199254740993n (Correct!)
💡 BigInt allows you to perform exact integer math on numbers larger than what the standard `Number` type can handle.
// Example 2
// 2. No Mixing with Numbers
const big = 10n;
const num = 5;

// console.log(big + num); // ❌ TypeError
console.log(big + BigInt(num)); // ✅ 15n
💡 You cannot mix BigInts and regular Numbers in math operations to avoid accidental precision loss. You must explicitly convert one type to the other.
// Example 3
// 3. Integer Division
console.log(5n / 2n); // 2n (Not 2.5n!)
💡 Division with BigInts always rounds towards zero (it truncates the decimal) because BigInt only represents whole integers.

Engine & Memory Architecture

Arbitrary Precision Storage

1. Variable Sizing:

  • Unlike Numbers (which are always 8 bytes), BigInts are stored in the Heap as a dynamically sized structure.
  • The more digits you have, the more RAM the BigInt consumes.

2. Storage Format:

  • Internally, BigInts are stored as an array of "digits" (usually in base 2^32 or base 2^64).
  • The engine uses Arbitrary-Precision Arithmetic algorithms to perform operations on these arrays.

3. Performance:

  • BigInt math is significantly slower than standard Number math because it cannot be performed in a single CPU instruction. It requires multiple cycles to process the digit arrays.