JavaScript BigInt and Number Arithmetic Guide

JavaScript does not allow implicit mixing of BigInt and standard Number types in arithmetic operations. Attempting to perform calculations directly between a BigInt and a Number throws a runtime TypeError to prevent accidental precision loss. To perform arithmetic with both types, you must explicitly convert them to a single common type before evaluating the expression.

The Mixed Type Restriction

When evaluating binary arithmetic operators (+, -, *, /, %, **), JavaScript enforces strict type consistency between BigInt and Number.

const bigValue = 100n;
const numValue = 50;

// Throws TypeError: Cannot mix BigInt and other types, use explicit conversions
const result = bigValue + numValue; 

JavaScript enforces this rule because standard numbers use 64-bit floating-point precision (IEEE 754), while BigInt represents arbitrary-precision integers. Silently coercing one type to the other could lead to unexpected rounding errors or truncated data.

Resolving Mixed Operations with Explicit Conversion

To execute arithmetic operations, explicitly cast one value to match the other. The conversion direction depends on whether your calculation requires arbitrary precision or standard floating-point behavior.

1. Converting Number to BigInt

Convert the Number to a BigInt when you need exact integer arithmetic without precision loss.

const bigValue = 100n;
const numValue = 50;

const result = bigValue + BigInt(numValue); // 150n (BigInt)

Note: Passing a non-integer or float to BigInt() throws a RangeError.

BigInt(10.5); // Throws RangeError: The number 10.5 cannot be converted to a BigInt because it is not an integer

2. Converting BigInt to Number

Convert the BigInt to a Number when your application requires floating-point operations or integration with APIs that do not support BigInt.

const bigValue = 100n;
const numValue = 50;

const result = Number(bigValue) + numValue; // 150 (Number)

Warning: Converting a BigInt larger than Number.MAX_SAFE_INTEGER (2^53 - 1) to a Number results in precision loss.

BigInt Division Behavior

Arithmetic involving BigInt values always rounds towards zero, dropping any fractional remainder.

const result = 5n / 2n; 
console.log(result); // 2n (fractional .5 is discarded)

If floating-point division is required, both operands must be converted to standard Number instances:

const result = Number(5n) / Number(2n);
console.log(result); // 2.5

Comparisons vs. Arithmetic

While arithmetic operations throw errors on mixed types, comparison operations do not require explicit conversion: