Bigint Handles Integers Beyond Safe Range

Use BigInt once integers exceed Number.MAX_SAFE_INTEGER: exact arithmetic, explicit conversions, and a TypeError when mixing the two types.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
const limit = Number.MAX_SAFE_INTEGER;
console.log('safe limit:', limit);

// 超出安全区间的 Number 会失真:相邻两个数加出来相等
console.log('number distorts:', limit + 1 === limit + 2);
console.log('bigint exact:', BigInt(limit) + 1n === BigInt(limit) + 2n);

const productId = 9007199254740993n;
console.log('id as number:', Number(productId));
console.log('id as bigint:', productId.toString());

// BigInt 与 Number 不能直接混合运算,先显式转换
try {
  1n + 1;
} catch (error) {
  console.log('mixing throws TypeError:', error instanceof TypeError);
}
console.log('explicit convert:', 1n + BigInt(1));

How it works

Module-level bindings hold the data — limit, productId — with no function scope in between.

Putting it to use

Each run prints the 7 labeled blocks safe limit:, number distorts:, bigint exact:, id as number:, id as bigint:, mixing throws TypeError:, explicit convert: in source order.

Core lines

const limit = Number.MAX_SAFE_INTEGER;
const productId = 9007199254740993n;

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `limit`, `productId`.