63. How does JavaScript handle big integers (BigInt)?
medium

A BigInt is a primitive type specifically designed to represent numeric values that are too large to be handled by the standard Number type.


Creating BigInts:

Using an integer literal:

const hugeNumber = 9007199254740991n; // 9007199254740991n

Using the BigInt() function:

const alsoHuge = BigInt(9007199254740991); // 9007199254740991n
const hugeString = BigInt("9007199254740991"); // 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff"); // 9007199254740991n
const hugeOctal = BigInt("0o377777777777777777"); // 9007199254740991n
const hugeBin = BigInt("0b111111111111111111111111111111111
11111111111111111111"); // 9007199254740991n

Key Differences from Number:


Math Operations: You can’t directly use BigInts with methods in the built-in Math object or mix them with Number values in operations. They must be coerced to the same type.

Type Information: When tested with typeof, a BigInt value returns “bigint”.

Operators: Most operators support BigInts, but they don’t allow mixed types. For example:

  • Arithmetic operators: +, -, *, /, %, **
  • Bitwise operators: >>, <<, &, |, ^
  • Unary negation (-)
  • Increment/decrement: ++, --

Special Cases:

Practical Examples:

Adding 1 to the maximum safe integer:

const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER); // 9007199254740991n
const maxPlusOne = previousMaxSafe + 1n; // 9007199254740992n
const theFuture = previousMaxSafe + 2n; // 9007199254740993n

Multiplying by 2:

const multi = previousMaxSafe * 2n; // 18014398509481982n

Subtracting 10:

const subtr = multi - 10n; // 18014398509481972n

Modulo 10:

const mod = multi % 10n; // 2n

Exponentiation:

const bigN = 2n ** 54n; // 18014398509481984n

Negation:

const negated = bigN * -1n; // -18014398509481984n

Division:

const expected = 4n / 2n; // 2n
const truncated = 5n / 2n; // 2n (not 2.5n)