Working with BigInt

BigInt is a built-in JavaScript type that allows you to represent integers with arbitrary precision, beyond the safe integer limit of Number.

Illustration of working_with_bigint
Illustration of working_with_bigint

💡 What is BigInt?

A numeric primitive to represent whole numbers larger than 253 - 1, which is the limit for the Number type.

Creating BigInt values

  • Append n to an integer literal: 123n
  • Use the BigInt() constructor: BigInt("9007199254740993")

📌 Deep Dive: Creating BigInt

JAVASCRIPT
const big1 = 9007199254740993n;
const big2 = BigInt("9007199254740993");
console.log(big1 === big2);
Output
true

Operations with BigInt

BigInt supports most arithmetic operators:

  • Addition: big1 + big2
  • Subtraction: big1 - big2
  • Multiplication: big1 * big2
  • Exponentiation: big1 ** 2n
  • Division (integer division): big1 / 2n (fractional part is discarded)

⚠️ Mixed Types in Operations

You cannot mix Number and BigInt types directly in arithmetic operations. Convert explicitly if needed.

📌 Deep Dive: Arithmetic with BigInt

JAVASCRIPT
const bigA = 10n;
const numB = 5;
// const result = bigA + numB; // TypeError: Cannot mix BigInt and other types
const result = bigA + BigInt(numB);
console.log(result);
Output
15n

Comparison with Number

BigInt can be compared with Number using relational operators, but strict equality (===) returns false.

Number vs BigInt Comparison
ExpressionResult
1n == 1true
1n === 1false
2n > 1true
1n < 2true

Type Conversion

  • Convert BigInt to Number: Number(bigIntValue) (may lose precision)
  • Convert Number to BigInt: BigInt(numberValue) (fractional numbers cause error)

⚠️ Caution with Conversion

Converting floating-point numbers to BigInt throws an error. Only integers are valid.

BigInt and JSON

BigInt values cannot be serialized with JSON.stringify() and will throw an error.

💡 Workaround for JSON

Convert BigInt to string before serialization, and convert back after parsing.

Summary

  • Use n suffix or BigInt() to create BigInt
  • BigInt supports arithmetic operators but no mixing with Number
  • Comparison works with Number but strict equality differs
  • Convert carefully between Number and BigInt
  • BigInt is not JSON serializable directly