JavaScript BigInt

Working with arbitrarily large integers in JavaScript

🔢 What is BigInt?

BigInt is a built-in object that provides a way to represent whole numbers larger than 2^53 - 1 (Number.MAX_SAFE_INTEGER). It can represent integers of arbitrary precision.


// Regular number limit
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991

// BigInt can go beyond this limit
let bigNumber = 9007199254740991n + 1n;
console.log(bigNumber); // 9007199254740992n
                                    

Output:

9007199254740991
9007199254740992n

Creating BigInt Values

📝

Literal Syntax

Add 'n' suffix to numbers

let big = 123456789012345678901234567890n;
🏗️

BigInt() Constructor

Convert numbers or strings

let big = BigInt("123456789012345678901234567890");
🔄

From Regular Numbers

Convert safe integers

let big = BigInt(123456789);
🎯

Binary/Hex

From different number bases

let big = BigInt("0x1fffffffffffff");

🔹 Creating BigInt Numbers

Different ways to create BigInt values:

// Using the 'n' suffix (literal)
let big1 = 123456789012345678901234567890n;
console.log("Literal BigInt:", big1);

// Using BigInt() constructor with string
let big2 = BigInt("987654321098765432109876543210");
console.log("From string:", big2);

// Using BigInt() constructor with number
let big3 = BigInt(123456789);
console.log("From number:", big3);

// From hexadecimal
let big4 = BigInt("0x1fffffffffffff");
console.log("From hex:", big4);

// From binary
let big5 = BigInt("0b11111111111111111111111111111111");
console.log("From binary:", big5);

// Cannot create from decimal numbers
try {
    let invalid = BigInt(3.14); // This will throw an error
} catch (error) {
    console.log("Error:", error.message);
}

Output:

Literal BigInt: 123456789012345678901234567890n
From string: 987654321098765432109876543210n
From number: 123456789n
From hex: 9007199254740991n
From binary: 4294967295n
Error: Cannot convert 3.14 to a BigInt

🔹 BigInt Operations

Mathematical operations with BigInt values:

let a = 123456789012345678901234567890n;
let b = 987654321098765432109876543210n;

// Addition
console.log("Addition:", a + b);

// Subtraction
console.log("Subtraction:", b - a);

// Multiplication
console.log("Multiplication:", a * 2n);

// Division (returns BigInt, truncates decimal)
console.log("Division:", b / 2n);

// Remainder
console.log("Remainder:", b % 3n);

// Exponentiation
console.log("Power:", 2n ** 100n);

// Cannot mix BigInt with regular numbers
try {
    let invalid = a + 5; // This will throw an error
} catch (error) {
    console.log("Error:", error.message);
}

// Must convert first
let mixed = a + BigInt(5);
console.log("Mixed (converted):", mixed);

Output:

Addition: 1111111110111111111011111111100n
Subtraction: 864197532086419753208641975320n
Multiplication: 246913578024691357802469135780n
Division: 493827160549382716054938271605n
Remainder: 0n
Power: 1267650600228229401496703205376n
Error: Cannot mix BigInt and other types
Mixed (converted): 123456789012345678901234567895n

🔹 BigInt Comparisons

Comparing BigInt values with each other and regular numbers:

let big1 = 100n;
let big2 = 200n;
let regular = 100;

// BigInt to BigInt comparisons
console.log("100n === 100n:", 100n === 100n); // true
console.log("100n < 200n:", big1 < big2); // true
console.log("200n > 100n:", big2 > big1); // true

// BigInt to Number comparisons (loose equality)
console.log("100n == 100:", big1 == regular); // true
console.log("100n === 100:", big1 === regular); // false (different types)
console.log("100n < 150:", big1 < 150); // true
console.log("200n > 150:", big2 > 150); // true

// Type checking
console.log("typeof 100n:", typeof 100n); // "bigint"
console.log("typeof 100:", typeof 100); // "number"

// Sorting array with BigInt
let numbers = [300n, 100n, 200n, 50n];
numbers.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
console.log("Sorted BigInts:", numbers);

Output:

100n === 100n: true
100n < 200n: true
200n > 100n: true
100n == 100: true
100n === 100: false
100n < 150: true
200n > 150: true
typeof 100n: bigint
typeof 100: number
Sorted BigInts: [50n, 100n, 200n, 300n]

🔹 Converting BigInt

Converting between BigInt and other types:

let bigNum = 123456789012345678901234567890n;

// Convert BigInt to string
let str = bigNum.toString();
console.log("To string:", str);
console.log("String type:", typeof str);

// Convert to different bases
console.log("To binary:", bigNum.toString(2));
console.log("To hex:", bigNum.toString(16));
console.log("To octal:", bigNum.toString(8));

// Convert BigInt to Number (be careful with precision!)
let smallBig = 123n;
let num = Number(smallBig);
console.log("Small BigInt to Number:", num);
console.log("Number type:", typeof num);

// Large BigInt to Number loses precision
try {
    let largeNum = Number(bigNum);
    console.log("Large BigInt to Number:", largeNum); // Infinity or imprecise
} catch (error) {
    console.log("Conversion error:", error.message);
}

// Safe conversion check
function safeToNumber(bigint) {
    if (bigint <= Number.MAX_SAFE_INTEGER && bigint >= Number.MIN_SAFE_INTEGER) {
        return Number(bigint);
    } else {
        throw new Error("BigInt too large for safe Number conversion");
    }
}

console.log("Safe conversion:", safeToNumber(123n));

Output:

To string: 123456789012345678901234567890
String type: string
To binary: 1101111010110111100110100010101...
To hex: 18ee90ff6c373e0ed4e9d2
To octal: 15572674642125016355322
Small BigInt to Number: 123
Number type: number
Large BigInt to Number: 1.2345678901234568e+29
Safe conversion: 123

🔹 Practical BigInt Examples

Real-world applications of BigInt:

// Factorial of large numbers
function factorial(n) {
    if (n <= 1n) return 1n;
    return n * factorial(n - 1n);
}

console.log("Factorial of 20:", factorial(20n));

// Fibonacci sequence with large numbers
function fibonacci(n) {
    if (n <= 1n) return n;
    let a = 0n, b = 1n;
    for (let i = 2n; i <= n; i++) {
        [a, b] = [b, a + b];
    }
    return b;
}

console.log("100th Fibonacci number:", fibonacci(100n));

// Working with timestamps (microseconds)
let microsecondTimestamp = BigInt(Date.now()) * 1000n;
console.log("Microsecond timestamp:", microsecondTimestamp);

// Cryptocurrency calculations (working with wei - smallest unit of Ether)
function etherToWei(ether) {
    return BigInt(ether) * (10n ** 18n);
}

function weiToEther(wei) {
    return wei / (10n ** 18n);
}

let oneEther = etherToWei(1);
console.log("1 Ether in Wei:", oneEther);
console.log("Back to Ether:", weiToEther(oneEther));

// Large prime number check (simplified)
function isProbablyPrime(n) {
    if (n < 2n) return false;
    if (n === 2n) return true;
    if (n % 2n === 0n) return false;
    
    for (let i = 3n; i * i <= n; i += 2n) {
        if (n % i === 0n) return false;
    }
    return true;
}

let largePrime = 2n ** 127n - 1n; // Mersenne prime
console.log("Is large number prime?", isProbablyPrime(largePrime));

Output:

Factorial of 20: 2432902008176640000n
100th Fibonacci number: 354224848179261915075n
Microsecond timestamp: 1640995200000000n
1 Ether in Wei: 1000000000000000000n
Back to Ether: 1n
Is large number prime? true

🧠 Test Your Knowledge

How do you create a BigInt literal?