JavaScript BigInt Data Type

BigInt Basics - Arbitrarily Large Integers

BigInt is a built-in object introduced in ES2020 that provides a way to represent whole numbers larger than 2^53 - 1 (the largest number JavaScript can reliably represent with the Number primitive). BigInt can represent integers with arbitrary precision.

javascript
1// BigInt declaration with 'n' suffix
2let bigNumber = 1234567890123456789012345678901234567890n;
3let negativeBigInt = -987654321098765432109876543210n;
4let zeroBigInt = 0n;
5
6console.log(bigNumber);        // Output: 1234567890123456789012345678901234567890n
7console.log(negativeBigInt);   // Output: -987654321098765432109876543210n
8console.log(zeroBigInt);       // Output: 0n
9
10// Type checking
11console.log(typeof bigNumber); // Output: "bigint"
12console.log(typeof BigInt);    // Output: "function"
13
14// BigInt constructor
15let constructedBigInt = BigInt("9007199254740993");
16console.log(constructedBigInt); // Output: 9007199254740993n
17
18// Number.MAX_SAFE_INTEGER limitation
19console.log(Number.MAX_SAFE_INTEGER); // Output: 9007199254740991
20console.log(Number.MAX_SAFE_INTEGER + 1); // Output: 9007199254740992
21console.log(Number.MAX_SAFE_INTEGER + 2); // Output: 9007199254740992 (incorrect!)
22
23// BigInt handles large numbers correctly
24let safeBigInt = BigInt(Number.MAX_SAFE_INTEGER) + 2n;
25console.log(safeBigInt); // Output: 9007199254740993n (correct!)
26
27// BigInt values are truly arbitrary precision
28let hugeNumber = 1234567890123456789012345678901234567890123456789012345678901234567890n;
29console.log(hugeNumber); // Output: 1234567890123456789012345678901234567890123456789012345678901234567890n

BigInt Core Characteristics

  • Arbitrary Precision - Can represent integers of any size without precision loss
  • n Suffix - BigInt literals end with 'n' to distinguish from Numbers
  • Separate Type - BigInt is a separate primitive type, not a subtype of Number
  • No Floating Point - Only represents integers, no decimal or fractional parts

BigInt Creation Methods

BigInt values can be created using literal syntax with 'n' suffix, the BigInt() constructor, or by converting from other data types. Each method has specific use cases and considerations.

javascript
1// Method 1: BigInt literal with 'n' suffix (most common)
2let literalBigInt = 12345678901234567890n;
3let negativeLiteral = -42n;
4let binaryLiteral = 0b1101n;    // Binary: 13n
5let octalLiteral = 0o777n;      // Octal: 511n
6let hexLiteral = 0xFFn;         // Hexadecimal: 255n
7
8console.log(literalBigInt);     // Output: 12345678901234567890n
9console.log(negativeLiteral);   // Output: -42n
10console.log(binaryLiteral);     // Output: 13n
11console.log(octalLiteral);      // Output: 511n
12console.log(hexLiteral);        // Output: 255n
13
14// Method 2: BigInt constructor
15let fromString = BigInt("9007199254740993");
16let fromNumber = BigInt(42);
17let fromBoolean = BigInt(true);  // 1n
18
19console.log(fromString);         // Output: 9007199254740993n
20console.log(fromNumber);         // Output: 42n
21console.log(fromBoolean);        // Output: 1n
22
23// Method 3: From other numeric representations
24let scientificBigInt = BigInt("1e20");     // 100000000000000000000n
25let withUnderscores = 1_000_000_000n;     // 1000000000n (readability)
26
27console.log(scientificBigInt);   // Output: 100000000000000000000n
28console.log(withUnderscores);    // Output: 1000000000n
29
30// Method 4: Converting from Number (be careful with unsafe integers)
31let safeNumber = 42;
32let safeConversion = BigInt(safeNumber); // 42n
33
34let unsafeNumber = 9007199254740993;     // Beyond safe integer range
35let unsafeConversion = BigInt(unsafeNumber); // 9007199254740992n (incorrect!)
36
37console.log(safeConversion);     // Output: 42n
38console.log(unsafeConversion);   // Output: 9007199254740992n (wrong due to Number precision)
39
40// Correct way for large numbers
41let correctBigInt = BigInt("9007199254740993"); // 9007199254740993n (correct!)
42
43// Method 5: Using BigInt.asIntN() and BigInt.asUintN()
44let clamped64 = BigInt.asIntN(64, 12345678901234567890n);
45let clamped32 = BigInt.asUintN(32, 5000000000n);
46
47console.log(clamped64);          // Output: 12345678901234567890n
48console.log(clamped32);          // Output: 705032704n (wraps around)
49
50// Invalid BigInt creations
51// let invalid1 = BigInt(3.14);    // TypeError: Cannot convert 3.14 to a BigInt
52// let invalid2 = BigInt("hello"); // SyntaxError: Cannot convert hello to a BigInt
53// let invalid3 = 3.14n;           // SyntaxError: Invalid BigInt literal

BigInt Creation Methods

  • Literal Syntax - Append 'n' to integer: 123n, supports binary, octal, hex
  • BigInt Constructor - BigInt(value) converts strings, numbers, booleans to BigInt
  • String Conversion - Always use strings for numbers beyond safe integer range
  • Bit Clamping - BigInt.asIntN()/asUintN() wrap values to specific bit sizes

BigInt Operations and Arithmetic

BigInt supports most arithmetic operations similar to regular numbers, but with some important differences and restrictions. BigInt operations always return BigInt values.

javascript
1let a = 12345678901234567890n;
2let b = 9876543210987654321n;
3
4// Basic arithmetic operations
5let sum = a + b;                // Addition
6let difference = a - b;         // Subtraction  
7let product = a * b;            // Multiplication
8let quotient = a / b;           // Division (integer division)
9let remainder = a % b;          // Modulus
10let power = a ** 2n;            // Exponentiation
11
12console.log(sum);               // Output: 22222222112222222211n
13console.log(difference);        // Output: 2469135690246913579n
14console.log(product);           // Output: 12193263113702179522374638011126352690n
15console.log(quotient);          // Output: 1n (integer division)
16console.log(remainder);         // Output: 2469135690246913569n
17console.log(power);             // Output: 152415787532388367501905199875019052100n
18
19// Unary operators
20let negative = -a;              // Output: -12345678901234567890n
21let positive = +a;              // Note: + operator not allowed with BigInt
22
23// Increment and decrement
24let counter = 0n;
25counter++;                      // 1n
26counter--;                      // 0n
27++counter;                      // 1n
28--counter;                      // 0n
29
30// Bitwise operations
31let bitwiseAnd = a & b;         // Bitwise AND
32let bitwiseOr = a | b;          // Bitwise OR
33let bitwiseXor = a ^ b;         // Bitwise XOR
34let bitwiseNot = ~a;            // Bitwise NOT
35let leftShift = a << 2n;        // Left shift
36let rightShift = a >> 2n;       // Right shift
37
38console.log(bitwiseAnd);        // Output: 3550288396458673152n
39console.log(bitwiseOr);         // Output: 18669948314773548059n
40console.log(bitwiseXor);        // Output: 15119659918314874907n
41console.log(bitwiseNot);        // Output: -12345678901234567891n
42console.log(leftShift);         // Output: 49382715604938271560n
43console.log(rightShift);        // Output: 3086419725308641972n
44
45// Comparison operations (work with both BigInt and Number)
46let smallBigInt = 100n;
47let regularNumber = 100;
48
49console.log(smallBigInt == regularNumber);   // Output: true
50console.log(smallBigInt === regularNumber);  // Output: false (different types)
51console.log(smallBigInt > 50);               // Output: true
52console.log(smallBigInt <= 100n);            // Output: true
53
54// Math operations that DON'T work with BigInt
55// console.log(Math.sqrt(a));                // TypeError: Cannot convert a BigInt value
56// console.log(a / 2);                       // TypeError: Cannot mix BigInt and other types
57
58// Correct way to do "floating-point-like" division
59let dividend = 17n;
60let divisor = 3n;
61let bigIntQuotient = dividend / divisor;     // 5n (integer division)
62let bigIntRemainder = dividend % divisor;    // 2n
63
64console.log(`Result: ${bigIntQuotient} remainder ${bigIntRemainder}`);
65// Output: Result: 5n remainder 2n

BigInt Operation Rules

  • Pure BigInt Operations - All operands must be BigInt; no mixing with Number types
  • Integer Division - Division truncates to integer; no fractional results
  • No Math Object - Math functions don't work with BigInt; implement manually
  • Comparison Works - Can compare BigInt with Number using ==, >, <, etc.

BigInt Conversion and Type Coercion

Converting between BigInt and other data types requires explicit methods. BigInt has specific coercion rules and doesn't automatically convert in most operations.

javascript
1let bigValue = 12345678901234567890n;
2
3// Converting BigInt to String
4let asString = bigValue.toString();
5let templateString = `The value is: ${bigValue}`;
6let explicitString = String(bigValue);
7
8console.log(asString);          // Output: "12345678901234567890"
9console.log(templateString);    // Output: "The value is: 12345678901234567890"
10console.log(explicitString);    // Output: "12345678901234567890"
11
12// Converting BigInt to Number (with caution)
13let smallBigInt = 42n;
14let asNumber = Number(smallBigInt);
15
16let hugeBigInt = 12345678901234567890n;
17let hugeAsNumber = Number(hugeBigInt); // Precision loss!
18
19console.log(asNumber);          // Output: 42
20console.log(hugeAsNumber);      // Output: 12345678901234567000 (precision lost)
21
22// Boolean conversion
23let zeroBigInt = 0n;
24let nonZeroBigInt = 1n;
25
26console.log(Boolean(zeroBigInt));      // Output: false
27console.log(Boolean(nonZeroBigInt));   // Output: true
28console.log(!!zeroBigInt);             // Output: false
29console.log(!!nonZeroBigInt);          // Output: true
30
31// JSON serialization issues
32let data = {
33    regularNumber: 42,
34    bigIntValue: bigValue
35};
36
37// console.log(JSON.stringify(data)); // TypeError: Do not know how to serialize a BigInt
38
39// Custom JSON serialization for BigInt
40function bigIntReplacer(key, value) {
41    if (typeof value === 'bigint') {
42        return value.toString() + 'n';
43    }
44    return value;
45}
46
47let serialized = JSON.stringify(data, bigIntReplacer);
48console.log(serialized); // Output: {"regularNumber":42,"bigIntValue":"12345678901234567890n"}
49
50// Custom JSON parsing for BigInt
51function bigIntReviver(key, value) {
52    if (typeof value === 'string' && value.endsWith('n')) {
53        return BigInt(value.slice(0, -1));
54    }
55    return value;
56}
57
58let parsed = JSON.parse(serialized, bigIntReviver);
59console.log(parsed.bigIntValue); // Output: 12345678901234567890n
60
61// Type coercion in comparisons
62let bigInt100 = 100n;
63let number100 = 100;
64
65console.log(bigInt100 == number100);   // Output: true (loose equality)
66console.log(bigInt100 === number100);  // Output: false (strict equality)
67console.log(bigInt100 > 99);           // Output: true
68console.log(bigInt100 < 101);          // Output: true
69
70// Explicit conversion functions
71function toBigIntSafely(value) {
72    if (typeof value === 'bigint') return value;
73    if (typeof value === 'number' && Number.isInteger(value)) return BigInt(value);
74    if (typeof value === 'string' && /^-?\d+n?$/.test(value)) {
75        return BigInt(value.replace('n', ''));
76    }
77    throw new TypeError(`Cannot convert ${value} to BigInt`);
78}
79
80console.log(toBigIntSafely(42));       // Output: 42n
81console.log(toBigIntSafely("123"));    // Output: 123n
82console.log(toBigIntSafely("456n"));   // Output: 456n

Practical BigInt Use Cases

BigInt is essential for applications dealing with large numbers, cryptography, financial calculations, scientific computing, and any domain where integer precision matters beyond 64-bit limits.

javascript
1// Use Case 1: Financial calculations with large currency values
2function calculateCompoundInterest(principal, rate, time) {
3    // Convert to smallest unit (cents/pence) to avoid floating point issues
4    let principalCents = BigInt(principal * 100);
5    let rateBigInt = BigInt(Math.round(rate * 10000)); // Convert to basis points
6    
7    let amount = principalCents;
8    for (let i = 0; i < time; i++) {
9        let interest = (amount * rateBigInt) / 10000n;
10        amount += interest;
11    }
12    
13    return Number(amount) / 100; // Convert back to dollars
14}
15
16// Use Case 2: Cryptography and large prime numbers
17function isProbablePrime(n, k = 5) {
18    if (n <= 1n) return false;
19    if (n <= 3n) return true;
20    if (n % 2n === 0n) return false;
21    
22    // Write n as 2^r * d + 1
23    let d = n - 1n;
24    let r = 0n;
25    while (d % 2n === 0n) {
26        d /= 2n;
27        r++;
28    }
29    
30    // Miller-Rabin primality test
31    for (let i = 0; i < k; i++) {
32        let a = BigInt(Math.floor(Math.random() * (Number(n - 2n))) + 2n;
33        let x = modPow(a, d, n);
34        
35        if (x === 1n || x === n - 1n) continue;
36        
37        let continueLoop = false;
38        for (let j = 0n; j < r - 1n; j++) {
39            x = modPow(x, 2n, n);
40            if (x === n - 1n) {
41                continueLoop = true;
42                break;
43            }
44        }
45        if (!continueLoop) return false;
46    }
47    return true;
48}
49
50function modPow(base, exponent, modulus) {
51    let result = 1n;
52    base = base % modulus;
53    while (exponent > 0n) {
54        if (exponent % 2n === 1n) {
55            result = (result * base) % modulus;
56        }
57        exponent = exponent >> 1n;
58        base = (base * base) % modulus;
59    }
60    return result;
61}
62
63let largePrime = 170141183460469231731687303715884105727n; // Known prime
64console.log(isProbablePrime(largePrime)); // Output: true
65
66// Use Case 3: Scientific computing with large integers
67function factorialBigInt(n) {
68    if (n <= 1n) return 1n;
69    let result = 1n;
70    for (let i = 2n; i <= n; i++) {
71        result *= i;
72    }
73    return result;
74}
75
76let fact100 = factorialBigInt(100n);
77console.log(`100! has ${fact100.toString().length} digits`);
78// Output: 100! has 158 digits
79
80// Use Case 4: Database IDs and unique identifiers
81class SnowflakeID {
82    constructor() {
83        this.epoch = 1609459200000n; // Custom epoch
84        this.sequence = 0n;
85        this.lastTimestamp = 0n;
86    }
87    
88    generate() {
89        let timestamp = BigInt(Date.now());
90        
91        if (timestamp === this.lastTimestamp) {
92            this.sequence = (this.sequence + 1n) & 4095n; // 12-bit sequence
93            if (this.sequence === 0n) {
94                // Wait for next millisecond
95                while (timestamp <= this.lastTimestamp) {
96                    timestamp = BigInt(Date.now());
97                }
98            }
99        } else {
100            this.sequence = 0n;
101        }
102        
103        this.lastTimestamp = timestamp;
104        
105        return ((timestamp - this.epoch) << 22n) | 
106               (1n << 17n) | // Machine ID (simplified)
107               this.sequence;
108    }
109}
110
111let snowflake = new SnowflakeID();
112let id = snowflake.generate();
113console.log(id); // Output: Large unique ID as BigInt
114
115// Use Case 5: Handling large timestamps and durations
116const NANOSECONDS_PER_SECOND = 1_000_000_000n;
117const MICROSECONDS_PER_SECOND = 1_000_000n;
118
119function nanosecondsToSeconds(ns) {
120    return ns / NANOSECONDS_PER_SECOND;
121}
122
123function highPrecisionTimer() {
124    let start = process.hrtime.bigint(); // Returns BigInt in nanoseconds
125    
126    // Simulate some work
127    let sum = 0n;
128    for (let i = 0n; i < 1000000n; i++) {
129        sum += i;
130    }
131    
132    let end = process.hrtime.bigint();
133    let duration = end - start;
134    
135    console.log(`Operation took ${duration} nanoseconds`);
136    console.log(`That's ${nanosecondsToSeconds(duration)} seconds`);
137    return duration;
138}
139
140// highPrecisionTimer(); // Uncomment in Node.js environment

BigInt Best Practices and Patterns

Following best practices when working with BigInt ensures code reliability, performance, and maintainability. Proper error handling and type checking are crucial when dealing with large numbers.

javascript
1// Best Practice 1: Use descriptive variable names
2const USER_ID = 12345678901234567890n;          // GOOD
3const TRANSACTION_AMOUNT_CENTS = 999999999999n; // GOOD
4
5// const big1 = 12345678901234567890n;          // BAD - unclear
6// const num = 999999999999n;                   // BAD - ambiguous
7
8// Best Practice 2: Always use strings for very large numbers
9const HUGE_NUMBER = BigInt("123456789012345678901234567890"); // GOOD
10// const HUGE_NUMBER = 123456789012345678901234567890n;       // ALSO GOOD
11
12// Avoid converting unsafe Numbers to BigInt
13let unsafeNumber = 9007199254740993;            // Beyond safe integer range
14// let badBigInt = BigInt(unsafeNumber);        // WRONG - precision lost
15let goodBigInt = BigInt("9007199254740993");    // CORRECT - use string
16
17// Best Practice 3: Implement type checking and conversion utilities
18function ensureBigInt(value) {
19    if (typeof value === 'bigint') return value;
20    
21    if (typeof value === 'number') {
22        if (!Number.isInteger(value)) {
23            throw new TypeError(`Number ${value} must be an integer`);
24        }
25        if (!Number.isSafeInteger(value)) {
26            console.warn(`Number ${value} is beyond safe integer range, precision may be lost`);
27        }
28        return BigInt(value);
29    }
30    
31    if (typeof value === 'string') {
32        if (!/^-?\d+n?$/.test(value)) {
33            throw new TypeError(`String "${value}" cannot be converted to BigInt`);
34        }
35        return BigInt(value.replace('n', ''));
36    }
37    
38    throw new TypeError(`Cannot convert ${typeof value} to BigInt`);
39}
40
41console.log(ensureBigInt(42));      // Output: 42n
42console.log(ensureBigInt("123"));   // Output: 123n
43
44// Best Practice 4: Handle BigInt in JSON properly
45const BigIntJSON = {
46    stringify(obj) {
47        return JSON.stringify(obj, (key, value) => {
48            if (typeof value === 'bigint') {
49                return { __type: 'BigInt', value: value.toString() };
50            }
51            return value;
52        });
53    },
54    
55    parse(json) {
56        return JSON.parse(json, (key, value) => {
57            if (value && value.__type === 'BigInt') {
58                return BigInt(value.value);
59            }
60            return value;
61        });
62    }
63};
64
65let dataWithBigInt = {
66    id: 12345678901234567890n,
67    name: "Large ID Object"
68};
69
70let serialized = BigIntJSON.stringify(dataWithBigInt);
71let deserialized = BigIntJSON.parse(serialized);
72console.log(deserialized.id); // Output: 12345678901234567890n
73
74// Best Practice 5: Use appropriate numeric separators for readability
75const MILLION = 1_000_000n;                     // GOOD
76const BILLION = 1_000_000_000n;                 // GOOD
77const TRILLION = 1_000_000_000_000n;            // GOOD
78
79// const hardToRead = 1000000000000n;           // BAD - hard to count zeros
80
81// Best Practice 6: Implement BigInt math utilities
82const BigIntMath = {
83    min(...values) {
84        return values.reduce((min, val) => val < min ? val : min);
85    },
86    
87    max(...values) {
88        return values.reduce((max, val) => val > max ? val : max);
89    },
90    
91    abs(value) {
92        return value < 0n ? -value : value;
93    },
94    
95    sign(value) {
96        if (value === 0n) return 0n;
97        return value > 0n ? 1n : -1n;
98    }
99};
100
101console.log(BigIntMath.min(100n, 50n, 200n));   // Output: 50n
102console.log(BigIntMath.max(100n, 50n, 200n));   // Output: 200n
103console.log(BigIntMath.abs(-123n));             // Output: 123n
104console.log(BigIntMath.sign(-456n));            // Output: -1n
105
106// Best Practice 7: Use BigInt only when necessary
107function calculateSum(numbers) {
108    // Check if we need BigInt
109    const needsBigInt = numbers.some(n => 
110        typeof n === 'number' && !Number.isSafeInteger(n)
111    ) || numbers.some(n => typeof n === 'bigint');
112    
113    if (needsBigInt) {
114        return numbers.reduce((sum, n) => {
115            const bigN = typeof n === 'bigint' ? n : BigInt(n);
116            return sum + bigN;
117        }, 0n);
118    } else {
119        return numbers.reduce((sum, n) => sum + n, 0);
120    }
121}
122
123console.log(calculateSum([1, 2, 3]));                    // Output: 6 (Number)
124console.log(calculateSum([9007199254740991, 1]));        // Output: 9007199254740992n (BigInt)
125
126// Best Practice 8: Document BigInt usage clearly
127/**
128 * Represents a large unique identifier
129 * @typedef {bigint} BigIntID
130 */
131
132/**
133 * Creates a user with a BigInt ID
134 * @param {BigIntID} id - The user's unique identifier
135 * @param {string} name - The user's name
136 * @returns {Object} User object
137 */
138function createUser(id, name) {
139    return { id, name };
140}

BigInt Limitations and Considerations

While BigInt is powerful, it has important limitations and differences from regular Numbers. Understanding these constraints helps avoid unexpected behavior in your applications.

javascript
1// Limitation 1: No built-in Math object support
2let bigValue = 100n;
3
4// These will all throw TypeError:
5// console.log(Math.sqrt(bigValue));
6// console.log(Math.pow(bigValue, 2n));
7// console.log(Math.abs(bigValue));
8
9// Manual implementations needed
10function bigIntSqrt(n) {
11    if (n < 0n) throw new Error('Negative numbers not supported');
12    if (n < 2n) return n;
13    
14    let x = n;
15    let y = (x + 1n) / 2n;
16    while (y < x) {
17        x = y;
18        y = (x + n / x) / 2n;
19    }
20    return x;
21}
22
23console.log(bigIntSqrt(16n)); // Output: 4n
24
25// Limitation 2: No mixing with Number in operations
26let bigInt = 100n;
27let number = 50;
28
29// These will throw TypeError:
30// let sum = bigInt + number;
31// let product = bigInt * number;
32// let division = bigInt / number;
33
34// Must explicitly convert
35let correctSum = bigInt + BigInt(number);        // 150n
36let correctProduct = bigInt * BigInt(number);    // 5000n
37
38console.log(correctSum);     // Output: 150n
39console.log(correctProduct); // Output: 5000n
40
41// Limitation 3: JSON serialization doesn't support BigInt
42let data = {
43    regular: 42,
44    bigInt: 12345678901234567890n
45};
46
47// console.log(JSON.stringify(data)); // TypeError
48
49// Limitation 4: Bitwise operations have different semantics
50let numberBitwise = ~100;        // -101 (32-bit two's complement)
51let bigIntBitwise = ~100n;       // -101n (infinite precision)
52
53console.log(numberBitwise);      // Output: -101
54console.log(bigIntBitwise);      // Output: -101n
55
56// Limitation 5: No implicit conversion in loose equality
57let looseEq = 100n == 100;       // true
58let strictEq = 100n === 100;     // false
59
60console.log(looseEq);            // Output: true
61console.log(strictEq);           // Output: false
62
63// Limitation 6: Performance considerations
64function benchmark() {
65    const iterations = 1000000;
66    
67    // Number operations
68    let numberStart = Date.now();
69    let numberSum = 0;
70    for (let i = 0; i < iterations; i++) {
71        numberSum += i;
72    }
73    let numberTime = Date.now() - numberStart;
74    
75    // BigInt operations
76    let bigIntStart = Date.now();
77    let bigIntSum = 0n;
78    for (let i = 0n; i < BigInt(iterations); i++) {
79        bigIntSum += i;
80    }
81    let bigIntTime = Date.now() - bigIntStart;
82    
83    console.log(`Number time: ${numberTime}ms`);
84    console.log(`BigInt time: ${bigIntTime}ms`);
85    console.log(`BigInt is ~${(bigIntTime / numberTime).toFixed(1)}x slower`);
86}
87
88// benchmark(); // Uncomment to run performance test
89
90// Limitation 7: Browser and environment support
91function checkBigIntSupport() {
92    try {
93        return typeof BigInt !== 'undefined' && 
94               typeof 1n !== 'undefined' &&
95               eval('typeof 1n') === 'bigint';
96    } catch (e) {
97        return false;
98    }
99}
100
101console.log(`BigInt support: ${checkBigIntSupport()}`);
102
103// Limitation 8: Library compatibility
104// Many existing libraries may not handle BigInt properly
105function safeLibraryCall(value) {
106    // Convert to string for libraries that don't support BigInt
107    if (typeof value === 'bigint') {
108        return value.toString();
109    }
110    return value;
111}
112
113// Workaround for common operations
114const BigIntWorkarounds = {
115    // Simulate Math.max for BigInt
116    max(...values) {
117        return values.reduce((a, b) => a > b ? a : b);
118    },
119    
120    // Simulate Math.min for BigInt
121    min(...values) {
122        return values.reduce((a, b) => a < b ? a : b);
123    },
124    
125    // Calculate absolute value
126    abs(value) {
127        return value < 0n ? -value : value;
128    }
129};

JavaScript BigInt FAQ

What is BigInt in JavaScript?

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 with arbitrary precision, meaning it can handle numbers of any size without precision loss.

When should I use BigInt instead of Number?

Use BigInt when you need to work with integers larger than 9 quadrillion (2^53 - 1), when precision is critical for financial calculations, cryptography, scientific computing, or when dealing with large IDs/timestamps that exceed safe integer range.

How do I create a BigInt value?

You can create BigInt by appending 'n' to an integer literal (123n), using the BigInt() constructor (BigInt(123)), or converting from a string (BigInt('123')). For numbers beyond safe integer range, always use string conversion.

Can I mix BigInt and Number in operations?

No, you cannot mix BigInt and Number in arithmetic operations. You must explicitly convert one type to the other using BigInt() or Number() constructor. However, comparisons (==, >, <) work between BigInt and Number.

Does BigInt support decimal numbers?

No, BigInt only represents integers. Division operations truncate to integer values. If you need decimal precision, consider using libraries for decimal arithmetic or work with smallest units (like cents instead of dollars).

How does BigInt handle JSON serialization?

BigInt values are not natively supported by JSON.stringify(). You'll get a TypeError. You need to implement custom serialization using replacer functions that convert BigInt to strings or special marker objects.

What's the performance impact of using BigInt?

BigInt operations are generally slower than Number operations because they handle arbitrary precision. The performance difference varies by operation and number size, but can be 2-10x slower for basic arithmetic in typical use cases.

Can I use Math functions with BigInt?

No, Math functions like Math.sqrt(), Math.pow(), etc., do not work with BigInt. You need to implement these functions manually or use libraries that provide BigInt mathematical operations.

How do I check if a value is a BigInt?

Use typeof value === 'bigint'. This will return true for BigInt values. You can also use value instanceof BigInt, but typeof is more reliable and faster.

What browsers and environments support BigInt?

BigInt is supported in modern browsers (Chrome 67+, Firefox 68+, Safari 14+, Edge 79+) and Node.js (10.4+ with flag, 12+ stable). For older environments, you'll need transpilation or polyfills, though polyfills have limitations for true arbitrary precision.