|

JavaScript 51 🧬 BigInt

const big1 = 9007199254740993n;
const big2 = BigInt('9007199254740993');
const big3 = BigInt(42);

console.log(big1);
console.log(typeof big1);

console.log(big1 + 1n);
console.log(big1 * 2n);
console.log(big1 - 1n);
console.log(big1 / 2n);
console.log(big1 % 2n);
console.log(big1 ** 2n);

console.log(big1 > 9007199254740992n);
console.log(big1 === 9007199254740993n);

console.log(big1.toString());
console.log(big1.toString(16));
console.log(big1.toString(2));

console.log(Number(big1));
console.log(BigInt(Number.MAX_SAFE_INTEGER));

BigInt is a numeric type for arbitrary-precision integers. Where regular JavaScript numbers lose precision past 2^53 – 1, BigInt keeps exact values no matter how large. It’s the tool for cryptography, large IDs, precise timestamps in nanoseconds, and anywhere exact integer math matters.

Key point: BigInt and Number are different types. You can’t mix them in arithmetic without converting. Use BigInt when you need exact integers of any size; stick with Number for everything else.


a – What is BigInt

BigInt is a primitive type introduced in ES2020. It represents integers of arbitrary size — no upper limit except memory.

Creating BigInt values:

MethodExampleResult
Literal (with n)42n42n
From stringBigInt('42')42n
From numberBigInt(42)42n
From hex stringBigInt('0xFF')255n
From binary stringBigInt('0b1010')10n

Literal syntax — the n suffix:

const a = 42n;
const b = 9007199254740993n;
const c = 0xFFn;
const d = 0b1010n;
const e = 0o777n;

The n at the end marks it as a BigInt.

From string:

const a = BigInt('42');
const b = BigInt('9007199254740993');

console.log(a);
// [ 42n ]

console.log(b);
// [ 9007199254740993n ]

Strings can be arbitrarily long — perfect for IDs, hashes, and precise values.

From number:

const a = BigInt(42);
console.log(a);
// [ 42n ]

⚠️ Warning: BigInt(3.14) throws a RangeError — only integer numbers can convert:

BigInt(3.14);   // RangeError: The number 3.14 cannot be converted to a BigInt

Why BigInt exists:

JavaScript’s Number type has a limit — the largest safe integer is 2^53 – 1:

console.log(Number.MAX_SAFE_INTEGER);
// [ 9007199254740991 ]

console.log(Number.MAX_SAFE_INTEGER + 1);
// [ 9007199254740992 ]

console.log(Number.MAX_SAFE_INTEGER + 2);
// [ 9007199254740992 ]  ← precision lost!

Beyond that, additions and multiplications give wrong results. BigInt fixes this:

const big = 9007199254740991n;
console.log(big + 1n);
// [ 9007199254740992n ]

console.log(big + 2n);
// [ 9007199254740993n ]  ← exact!

BigInt vs Number:

FeatureNumberBigInt
Type64-bit floatArbitrary integer
Decimals
Range±1.79e+308Unlimited
Safe integersUp to 2^53Unlimited
OperationsFastSlower
Mix with other?❌ (TypeError)
JSON❌ (TypeError)
Math.* methods
typeof'number''bigint'

typeof BigInt:

console.log(typeof 42n);
// [ 'bigint' ]

console.log(typeof 42);
// [ 'number' ]

BigInt has its own type — not 'number'.

Equality:

console.log(42n === 42);
// [ false ]  ← different types

console.log(42n == 42);
// [ true ]  ← loose equality coerces

console.log(42n === BigInt(42));
// [ true ]  ← same type, same value

Use === to be safe — == coerces and can hide bugs.

BigInt has no decimals:

console.log(5n / 2n);
// [ 2n ]  ← integer division, truncates

console.log(5 / 2);
// [ 2.5 ]

Any operation that would produce a decimal produces an integer instead. BigInt is for exact integer math only.


b – BigInt operations and behavior

BigInt supports the same arithmetic operators as Number — but with important differences.

Arithmetic:

OperationExampleResult
Add2n + 3n5n
Subtract5n - 2n3n
Multiply4n * 5n20n
Divide10n / 3n3n (truncated)
Modulus10n % 3n1n
Power2n ** 10n1024n
Negate-5n-5n
Increment++xworks
Decrement--xworks

Examples:

console.log(2n + 3n);
// [ 5n ]

console.log(5n - 2n);
// [ 3n ]

console.log(4n * 5n);
// [ 20n ]

console.log(10n / 3n);
// [ 3n ]

console.log(10n % 3n);
// [ 1n ]

console.log(2n ** 10n);
// [ 1024n ]

BigInt and Number cannot mix:

console.log(1n + 1);
// TypeError: Cannot mix BigInt and other types

You must convert explicitly:

console.log(1n + BigInt(1));
// [ 2n ]

console.log(Number(1n) + 1);
// [ 2 ]

Comparison works across types:

console.log(1n < 2);
// [ true ]

console.log(2n > 1);
// [ true ]

console.log(1n == 1);
// [ true ]

console.log(1n === 1);
// [ false ]  ← different types

Comparison operators (<, >, <=, >=) work between BigInt and Number. Equality with === doesn’t.

Bitwise operations:

console.log(5n & 3n);
// [ 1n ]

console.log(5n | 3n);
// [ 7n ]

console.log(5n ^ 3n);
// [ 6n ]

console.log(~5n);
// [ -6n ]

console.log(1n << 4n);
// [ 16n ]

console.log(16n >> 2n);
// [ 4n ]

Same bitwise operators as Numbers, but the operands must all be BigInts.

Unary plus is not allowed:

console.log(+5n);
// TypeError: Cannot convert a BigInt value to a number

Use Number(5n) or BigInt(5) to convert.

Conversions:

// BigInt → Number
const n = Number(9007199254740993n);
// [ 9007199254740992 ] ⚠️ precision lost if too big

// BigInt → String
const s = 42n.toString();
// [ '42' ]

const hex = 255n.toString(16);
// [ 'ff' ]

const bin = 255n.toString(2);
// [ '11111111' ]

// String → BigInt
const b = BigInt('42');
// [ 42n ]

// Number → BigInt (must be integer)
const bn = BigInt(42);
// [ 42n ]

toString(base) works:

console.log(255n.toString(16));
// [ 'ff' ]

console.log(255n.toString(2));
// [ '11111111' ]

console.log(255n.toString(8));
// [ '377' ]

No Math methods:

Math.max(1n, 2n);
// TypeError: Cannot convert a BigInt value to a number

Math.* functions don’t work on BigInt. Write your own or convert.

No toFixed or toPrecision:

(42n).toFixed(2);
// TypeError: (42n).toFixed is not a function

BigInts are integers — no decimals, no formatting.

JSON doesn’t serialize BigInt:

JSON.stringify({ id: 42n });
// TypeError: Do not know how to serialize a BigInt

Convert to string first:

JSON.stringify({ id: 42n.toString() });
// [ '{"id":"42"}' ]

Or use a replacer:

JSON.stringify({ id: 42n }, (_, v) =>
  typeof v === 'bigint' ? v.toString() : v
);
// [ '{"id":"42"}' ]

Parsing BigInt from JSON:

const json = '{"id":"9007199254740993"}';
const data = JSON.parse(json);
const id = BigInt(data.id);

console.log(id);
// [ 9007199254740993n ]

BigInt cannot be used with Math.random:

Math.random() * 10n;
// TypeError

Common operations table:

OperationCodeResult
Sum2n + 3n5n
Product4n * 5n20n
Integer division10n / 3n3n
Modulus10n % 3n1n
Power2n ** 10n1024n
Compare1n < 2ntrue
Compare to number1n < 2true
Strict equality with number1n === 1false
Loose equality with number1n == 1true
Bitwise AND5n & 3n1n
Left shift1n << 4n16n

BigInt and arrays:

const arr = [1n, 2n, 3n];
console.log(arr.map(x => x * 2n));
// [ [ 2n, 4n, 6n ] ]

console.log(arr.reduce((a, b) => a + b, 0n));
// [ 6n ]

The initial reduce value must be 0n, not 0.

BigInt in sets:

const set = new Set([1n, 2n, 1n]);
console.log(set.size);
// [ 2 ]  ← 1n === 1n deduplicates

Sets work with BigInt values — but 1n and 1 are different.


c – When to use BigInt

BigInt isn’t for everything. It’s slower, more limited, and can’t be serialized to JSON without conversion. Use it only when you need it.

Use BigInt when:

Use caseWhy
IDs larger than 2^53Exact precision required
Database big integersMatch the DB type
CryptographyLarge prime numbers, keys
Nanosecond timestamps2^53 ns ≈ 104 days
Hash valuesSHA-256 is 256 bits
Precise countersBeyond MAX_SAFE_INTEGER
Financial amounts in smallest unitCents, satoshis, wei

Don’t use BigInt when:

Use caseUse instead
Prices in dollarsNumber + careful decimal handling
Scientific computationNumber
Game physicsNumber
Anything with decimalsNumber, or decimal library
Fast hot loopsNumber
Serialized dataNumber or String

The ID pattern — the classic BigInt use case:

const userId = 9007199254740993n;   // exceeds MAX_SAFE_INTEGER
console.log(userId);
// [ 9007199254740993n ]

console.log(userId + 1n);
// [ 9007199254740994n ]  ← exact

Twitter’s snowflake IDs, UUIDs converted to decimal, and many database IDs exceed 2^53.

Database example — the classic bug:

// PostgreSQL BIGINT ID returned as a JS number
const id = 9007199254740993;   // ❌ silently wrong!
console.log(id);
// [ 9007199254740992 ]  ← precision lost

// Fix: parse as BigInt
const id = BigInt('9007199254740993');
console.log(id);
// [ 9007199254740993n ]

This is why many APIs return big IDs as strings — JavaScript numbers can’t represent them.

Crypto — large primes:

function modPow(base, exp, mod) {
  let result = 1n;
  base = base % mod;
  while (exp > 0n) {
    if (exp % 2n === 1n) result = (result * base) % mod;
    exp = exp / 2n;
    base = (base * base) % mod;
  }
  return result;
}

const result = modPow(2n, 10n, 1000n);
console.log(result);
// [ 24n ]

Impossible with Number — precision would be lost.

Nanosecond timestamps:

const nowNs = BigInt(Date.now()) * 1_000_000n;
console.log(nowNs);
// [ 1705314600000000000n ]

Date.now() in nanoseconds is well past MAX_SAFE_INTEGER.

Factorial of large numbers:

function factorial(n) {
  let result = 1n;
  for (let i = 2n; i <= BigInt(n); i++) {
    result *= i;
  }
  return result;
}

console.log(factorial(50));
// [ 30414093201713378043612608166064768844377641568960512000000000000n ]

With Number, factorial(50) would be approximate. BigInt gives the exact value.

Fibonacci:

function fib(n) {
  let [a, b] = [0n, 1n];
  for (let i = 0; i < n; i++) {
    [a, b] = [b, a + b];
  }
  return a;
}

console.log(fib(100));
// [ 354224848179261915075n ]

Fib(100) is well past MAX_SAFE_INTEGER.

Counting — precise:

let count = 0n;
while (count < 10n) {
  count++;
}
console.log(count);
// [ 10n ]

For counters that might exceed 2^53 (page views, event counts, monetary units), BigInt guarantees precision.

Money in smallest unit:

const wei = 1_000_000_000_000_000_000n;   // 1 ETH in wei
const price = 250_000_000_000_000_000n;    // 0.25 ETH

console.log(wei + price);
// [ 1250000000000000000n ]

console.log(wei - price);
// [ 750000000000000000n ]

Cryptocurrency amounts are often too large for Number.

Serializing BigInt — the common pattern:

function replacer(key, value) {
  return typeof value === 'bigint' ? value.toString() : value;
}

const data = { id: 9007199254740993n, name: 'Alice' };
const json = JSON.stringify(data, replacer);
console.log(json);
// [ '{"id":"9007199254740993","name":"Alice"}' ]

const parsed = JSON.parse(json, (key, value) =>
  key === 'id' ? BigInt(value) : value
);
console.log(parsed.id);
// [ 9007199254740993n ]

Practical decision guide:

┌──────────────────────────────────────────────┐
│  Do you need integer precision > 2^53?       │
│                                              │
│  ┌──── yes ────┐         ┌──── no ────┐      │
│  │  BigInt     │         │  Number    │      │
│  └─────────────┘         └────────────┘      │
│                                              │
│  Do you need decimals?                       │
│                                              │
│  ┌──── yes ────┐         ┌──── no ────┐      │
│  │  Number or  │         │  BigInt    │      │
│  │  decimal lib│         │  possible  │      │
│  └─────────────┘         └────────────┘      │
│                                              │
└──────────────────────────────────────────────┘

BigInt in TypeScript:

const id: bigint = 42n;

function process(id: bigint): bigint {
  return id * 2n;
}

TypeScript has a bigint type.


Complete Example Session

// ============================================
// PART 1: CREATING BIGINT
// ============================================

const big1 = 9007199254740993n;
console.log(big1);
// [ 9007199254740993n ]

console.log(typeof big1);
// [ 'bigint' ]

const big2 = BigInt('9007199254740993');
console.log(big2);
// [ 9007199254740993n ]

const big3 = BigInt(42);
console.log(big3);
// [ 42n ]

// ============================================
// PART 2: ARITHMETIC
// ============================================

console.log(big1 + 1n);
// [ 9007199254740994n ]

console.log(big1 * 2n);
// [ 18014398509481986n ]

console.log(big1 - 1n);
// [ 9007199254740992n ]

console.log(big1 / 2n);
// [ 4503599627370496n ]

console.log(big1 % 2n);
// [ 1n ]

console.log(big1 ** 2n);
// [ 81129638414606681695789005144064n ]

// ============================================
// PART 3: COMPARISON
// ============================================

console.log(big1 > 9007199254740992n);
// [ true ]

console.log(big1 === 9007199254740993n);
// [ true ]

console.log(42n === 42);
// [ false ]

console.log(42n == 42);
// [ true ]

// ============================================
// PART 4: STRING CONVERSION
// ============================================

console.log(big1.toString());
// [ '9007199254740993' ]

console.log(big1.toString(16));
// [ '20000000000001' ]

console.log(big1.toString(2));
// [ '100000000000000000000000000000000000000000000000000001' ]

// ============================================
// PART 5: NUMBER CONVERSION
// ============================================

console.log(Number(big1));
// [ 9007199254740992 ]  ← precision lost

console.log(BigInt(Number.MAX_SAFE_INTEGER));
// [ 9007199254740991n ]

// ============================================
// PART 6: CANNOT MIX TYPES
// ============================================

try {
  console.log(1n + 1);
} catch (err) {
  console.log(err.message);
}
// [ Cannot mix BigInt and other types, use explicit conversions ]

// ============================================
// PART 7: BIGINT LITERALS
// ============================================

console.log(0xFFn);
// [ 255n ]

console.log(0b1010n);
// [ 10n ]

console.log(0o777n);
// [ 511n ]

// ============================================
// PART 8: BITWISE
// ============================================

console.log(5n & 3n);
// [ 1n ]

console.log(5n | 3n);
// [ 7n ]

console.log(5n ^ 3n);
// [ 6n ]

console.log(1n << 4n);
// [ 16n ]

// ============================================
// PART 9: NO MATH METHODS
// ============================================

try {
  Math.max(1n, 2n);
} catch (err) {
  console.log(err.message);
}
// [ Cannot convert a BigInt value to a number ]

// ============================================
// PART 10: NO DECIMALS
// ============================================

try {
  BigInt(3.14);
} catch (err) {
  console.log(err.message);
}
// [ The number 3.14 cannot be converted to a BigInt because it is not an integer ]

// ============================================
// PART 11: INTEGER DIVISION
// ============================================

console.log(5n / 2n);
// [ 2n ]

console.log(10n / 3n);
// [ 3n ]

// ============================================
// PART 12: FACTORIAL
// ============================================

function factorial(n) {
  let result = 1n;
  for (let i = 2n; i <= BigInt(n); i++) {
    result *= i;
  }
  return result;
}

console.log(factorial(20));
// [ 2432902008176640000n ]

// ============================================
// PART 13: FIBONACCI
// ============================================

function fib(n) {
  let [a, b] = [0n, 1n];
  for (let i = 0; i < n; i++) {
    [a, b] = [b, a + b];
  }
  return a;
}

console.log(fib(100));
// [ 354224848179261915075n ]

// ============================================
// PART 14: JSON SERIALIZATION
// ============================================

try {
  JSON.stringify({ id: 42n });
} catch (err) {
  console.log(err.message);
}
// [ Do not know how to serialize a BigInt ]

const replacer = (_, v) => typeof v === 'bigint' ? v.toString() : v;
console.log(JSON.stringify({ id: 42n }, replacer));
// [ '{"id":"42"}' ]

// ============================================
// PART 15: PARSING BIGINTS FROM JSON
// ============================================

const json = '{"id":"9007199254740993"}';
const parsed = JSON.parse(json, (k, v) =>
  k === 'id' ? BigInt(v) : v
);

console.log(parsed.id);
// [ 9007199254740993n ]

// ============================================
// PART 16: ARRAYS
// ============================================

const arr = [1n, 2n, 3n];
console.log(arr.map(x => x * 2n));
// [ [ 2n, 4n, 6n ] ]

console.log(arr.reduce((a, b) => a + b, 0n));
// [ 6n ]

// ============================================
// PART 17: SETS
// ============================================

const set = new Set([1n, 2n, 1n]);
console.log(set.size);
// [ 2 ]

console.log(set.has(1n));
// [ true ]

// ============================================
// PART 18: LARGE PRIME MOD
// ============================================

function modPow(base, exp, mod) {
  let result = 1n;
  base = base % mod;
  while (exp > 0n) {
    if (exp % 2n === 1n) result = (result * base) % mod;
    exp = exp / 2n;
    base = (base * base) % mod;
  }
  return result;
}

console.log(modPow(2n, 10n, 1000n));
// [ 24n ]

// ============================================
// PART 19: HUGE MULTIPLICATION
// ============================================

const a = 123456789012345678901234567890n;
const b = 987654321098765432109876543210n;

console.log(a * b);
// [ 121932631137021795226185032733622923332237463801111263526900n ]

// ============================================
// PART 20: FULL SCRIPT
// ============================================

const big1_51 = 9007199254740993n;
const big2_51 = BigInt('9007199254740993');
const big3_51 = BigInt(42);

console.log(big1_51);
console.log(typeof big1_51);

console.log(big1_51 + 1n);
console.log(big1_51 * 2n);
console.log(big1_51 - 1n);
console.log(big1_51 / 2n);
console.log(big1_51 % 2n);
console.log(big1_51 ** 2n);

console.log(big1_51 > 9007199254740992n);
console.log(big1_51 === 9007199254740993n);

console.log(big1_51.toString());
console.log(big1_51.toString(16));
console.log(big1_51.toString(2));

console.log(Number(big1_51));
console.log(BigInt(Number.MAX_SAFE_INTEGER));

Quick Reference

Creating BigInt

MethodExampleResult
Literal42n42n
From stringBigInt('42')42n
From numberBigInt(42)42n
Hex literal0xFFn255n
Binary literal0b1010n10n
Octal literal0o777n511n

Arithmetic

OperationCodeResult
Add2n + 3n5n
Subtract5n - 2n3n
Multiply4n * 5n20n
Divide10n / 3n3n
Modulus10n % 3n1n
Power2n ** 10n1024n
Negate-5n-5n
Incrementx++

Bitwise

OperationCodeResult
AND5n & 3n1n
OR5n | 3n7n
XOR5n ^ 3n6n
NOT~5n-6n
Left shift1n << 4n16n
Right shift16n >> 2n4n

Comparison

CodeResult
1n < 2ntrue
1n < 2true
1n == 1true
1n === 1false
1n === 1ntrue

Conversion

FromToCode
NumberBigIntBigInt(n)
StringBigIntBigInt('42')
BigIntNumberNumber(bn)
BigIntStringbn.toString()
BigIntHexbn.toString(16)
BigIntBinarybn.toString(2)

BigInt vs Number

FeatureNumberBigInt
Type'number''bigint'
Decimals
Range±1.79e+308Unlimited
Safe int2^53Unlimited
Mix
Math.*
JSON
SpeedFastSlower
Literal4242n

Use Cases

CaseUse BigInt?
IDs > 2^53
Crypto
Nanosecond ts
Large factorials
Prices (dollars)
Scientific
Game physics
JSON data❌ (use string)

Best Practices

Do This:

// Use n suffix for literals
const id = 42n;                                 // ✅

// Convert explicitly when mixing
1n + BigInt(1);                                 // ✅
Number(1n) + 1;                                 // ✅

// Use toString for JSON
JSON.stringify({ id: 42n.toString() });         // ✅

// Use a replacer for JSON
JSON.stringify(data, (_, v) =>
  typeof v === 'bigint' ? v.toString() : v);    // ✅

// Parse big integers from strings
BigInt('9007199254740993');                     // ✅

// Use BigInt for large IDs
const snowflake = BigInt(idString);             // ✅

// Compare with ===
42n === 42n;                                    // ✅

// Initialize reduce with 0n for BigInt arrays
arr.reduce((a, b) => a + b, 0n);                // ✅

Don’t Do This:

// Don't mix BigInt and Number
1n + 1;                                         // ❌ TypeError

// Don't use Math on BigInt
Math.max(1n, 2n);                               // ❌ TypeError

// Don't expect decimals
5n / 2n;                                        // ⚠️  2n, not 2.5

// Don't use with JSON.stringify
JSON.stringify({ id: 42n });                    // ❌ TypeError

// Don't convert large numbers carelessly
BigInt(9007199254740993);                       // ⚠️  argument already imprecise
BigInt('9007199254740993');                     // ✅

// Don't use unary plus
+5n;                                            // ❌ TypeError

// Don't use with Math.random
Math.random() * 10n;                            // ❌ TypeError

// Don't forget the `n` on literals
const x = 42;                                   // ⚠️  Number, not BigInt
const x = 42n;                                  // ✅

Common Pitfalls

PitfallProblemSolution
Mixing with NumberTypeErrorConvert explicitly
Math.* on BigIntTypeErrorUse arithmetic
+bigintTypeErrorUse Number(bn)
JSON.stringifyTypeErrorUse replacer
Forgot nNumber, not BigIntAdd n
BigInt(3.14)RangeErrorUse BigInt(str)
bigint.toFixedNot a methodUse toString
Reduce initial 0TypeErrorUse 0n
Loose equalityHides typeUse ===
Precise large IDsNumber loses precisionBigInt or string

Real-World Examples

1. Basic BigInt

const big = 9007199254740993n;
console.log(big);
// [ 9007199254740993n ]

2. From String

const big = BigInt('9007199254740993');
console.log(big);
// [ 9007199254740993n ]

3. Arithmetic

console.log(2n + 3n);
// [ 5n ]

console.log(4n * 5n);
// [ 20n ]

console.log(2n ** 10n);
// [ 1024n ]

4. Integer Division

console.log(10n / 3n);
// [ 3n ]

console.log(10n % 3n);
// [ 1n ]

5. Comparison

console.log(1n < 2n);
// [ true ]

console.log(42n === 42n);
// [ true ]

console.log(42n === 42);
// [ false ]

6. To String

console.log(255n.toString(16));
// [ 'ff' ]

console.log(255n.toString(2));
// [ '11111111' ]

7. Factorial

function factorial(n) {
  let r = 1n;
  for (let i = 2n; i <= BigInt(n); i++) r *= i;
  return r;
}

console.log(factorial(20));
// [ 2432902008176640000n ]

8. Fibonacci

function fib(n) {
  let [a, b] = [0n, 1n];
  for (let i = 0; i < n; i++) [a, b] = [b, a + b];
  return a;
}

console.log(fib(100));
// [ 354224848179261915075n ]

9. Large Multiplication

const a = 123456789012345678901234567890n;
const b = 987654321098765432109876543210n;
console.log(a * b);
// [ 121932631137021795226185032733622923332237463801111263526900n ]

10. ModPow

function modPow(b, e, m) {
  let r = 1n;
  b %= m;
  while (e > 0n) {
    if (e % 2n === 1n) r = (r * b) % m;
    e /= 2n;
    b = (b * b) % m;
  }
  return r;
}

console.log(modPow(2n, 10n, 1000n));
// [ 24n ]

11. JSON with Replacer

const data = { id: 42n, name: 'Alice' };
const json = JSON.stringify(data, (_, v) =>
  typeof v === 'bigint' ? v.toString() : v
);
console.log(json);
// [ '{"id":"42","name":"Alice"}' ]

12. Parse JSON with BigInt

const parsed = JSON.parse('{"id":"9007199254740993"}', (k, v) =>
  k === 'id' ? BigInt(v) : v
);
console.log(parsed.id);
// [ 9007199254740993n ]

13. Reduce BigInt Array

console.log([1n, 2n, 3n].reduce((a, b) => a + b, 0n));
// [ 6n ]

14. Bitwise

console.log(5n & 3n);   // 1n
console.log(5n | 3n);   // 7n
console.log(1n << 4n);  // 16n

15. Hex

const hex = 0xFFn;
console.log(hex);
// [ 255n ]

console.log(hex.toString(16));
// [ 'ff' ]

16. Nanosecond Timestamp

const nowNs = BigInt(Date.now()) * 1_000_000n;
console.log(nowNs);
// [ 1705314600000000000n ]

17. Currency in Smallest Unit

const wei = 1_000_000_000_000_000_000n;
const price = 250_000_000_000_000_000n;

console.log(wei - price);
// [ 750000000000000000n ]

18. Set of BigInts

const set = new Set([1n, 2n, 1n]);
console.log(set.size);
// [ 2 ]

19. Safe ID

function parseId(str) {
  try {
    return BigInt(str);
  } catch {
    return null;
  }
}

console.log(parseId('9007199254740993'));
// [ 9007199254740993n ]

console.log(parseId('not-a-number'));
// [ null ]

20. Full Script

const big1_51 = 9007199254740993n;
const big2_51 = BigInt('9007199254740993');
const big3_51 = BigInt(42);

console.log(big1_51);
console.log(typeof big1_51);

console.log(big1_51 + 1n);
console.log(big1_51 * 2n);
console.log(big1_51 - 1n);
console.log(big1_51 / 2n);
console.log(big1_51 % 2n);
console.log(big1_51 ** 2n);

console.log(big1_51 > 9007199254740992n);
console.log(big1_51 === 9007199254740993n);

console.log(big1_51.toString());
console.log(big1_51.toString(16));
console.log(big1_51.toString(2));

console.log(Number(big1_51));
console.log(BigInt(Number.MAX_SAFE_INTEGER));

Visual: Number vs BigInt

┌──────────────────────────────────────────────┐
│           Number                             │
│                                              │
│  64-bit floating-point                       │
│  ✅ Decimals                                 │
│  ✅ Fast                                     │
│  ✅ Math methods                             │
│  ❌ Precision past 2^53                       │
│  Range: ±1.79e+308                           │
│                                              │
└──────────────────────────────────────────────┘

┌──────────────────────────────────────────────┐
│           BigInt                             │
│                                              │
│  Arbitrary-size integer                      │
│  ❌ Decimals                                 │
│  ⚠️  Slower                                   │
│  ❌ Math methods                             │
│  ✅ Exact at any size                         │
│  Range: unlimited (memory-bound)             │
│                                              │
└──────────────────────────────────────────────┘

Visual: Precision Boundary

┌──────────────────────────────────────────────┐
│  Number.MAX_SAFE_INTEGER = 2^53 - 1          │
│    = 9007199254740991                        │
│                                              │
│  Below: exact integers                       │
│  Above: silently imprecise                   │
│                                              │
│  9007199254740991 + 1 = 9007199254740992 ✓   │
│  9007199254740992 + 1 = 9007199254740992 ✗   │
│                                              │
│  BigInt fixes this:                          │
│  9007199254740992n + 1n = 9007199254740993n ✓│
│                                              │
└──────────────────────────────────────────────┘

Visual: BigInt in JSON

┌──────────────────────────────────────────────┐
│  const data = { id: 42n };                   │
│                                              │
│  JSON.stringify(data)                        │
│    → TypeError: Do not know how to           │
│      serialize a BigInt                      │
│                                              │
│  Fix: convert to string                      │
│                                              │
│  JSON.stringify(data, (_, v) =>              │
│    typeof v === 'bigint' ? v.toString() : v  │
│  );                                          │
│    → '{"id":"42"}'                           │
│                                              │
└──────────────────────────────────────────────┘

Summary

ConceptSyntaxExample
Literal42nBigInt with n
From stringBigInt('42')Exact parse
From numberBigInt(42)Integer only
Arithmetic2n + 3n5n
Division10n / 3n3n
Power2n ** 10n1024n
Bitwise5n & 3n1n
Compare1n < 2ntrue
Loose eq with Number1n == 1true
Strict eq with Number1n === 1false
To stringbn.toString()'42'
To basebn.toString(16)'ff'
To NumberNumber(bn)May lose precision
typeoftypeof 42n'bigint'
Factorialn! for large nExact
CryptoModPowExact
JSONReplacerConvert to string

Key takeaways:

  • BigInt is a primitive type for arbitrary-precision integers
  • Create with the n suffix (42n), BigInt(str), or BigInt(number)
  • typeof 42n === 'bigint' — not 'number'
  • Can’t mix BigInt and Number in arithmetic — convert explicitly
  • No decimals — division truncates
  • No Math.* methods — implement your own
  • No JSON.stringify — use a replacer to convert to string
  • === with Number is false== coerces
  • Unary plus (+bn) throws
  • Use BigInt for large IDs, crypto, nanosecond timestamps, exact large counters
  • Don’t use BigInt for prices, scientific, game physics, or JSON data
  • APIs often return big IDs as strings — parse with BigInt(str) to preserve precision

Remember: BigInt fills the one gap in JavaScript numbers — precision past 2^53. Use it when you need exact integers of any size. Remember that BigInts don’t mix with Numbers, don’t have Math methods, don’t have decimals, and don’t serialize to JSON directly. For everything else, stick with Number. Master BigInt, and precision stops being a limit — it becomes a choice.


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!