阿里云主机折上折
  • 微信号
Current Site:Index > The new primitive data type BigInt

The new primitive data type BigInt

Author:Chuan Chen 阅读数:42705人阅读 分类: JavaScript

Background of BigInt Introduction in ECMAScript 11

JavaScript's Number type is based on the IEEE 754 double-precision floating-point standard, which can safely represent integers up to 2^53 - 1 (i.e., Number.MAX_SAFE_INTEGER). Beyond this range, calculation results may lose precision. The introduction of the BigInt type solves this problem by allowing the representation and manipulation of integers with arbitrary precision.

Basic Characteristics of BigInt

BigInt is a new primitive data type used to represent integers larger than 2^53 - 1. Its main differences from the Number type include:

  1. Literals end with n, e.g., 123n
  2. Cannot be mixed with Number types in operations
  3. Does not support methods from the Math object
  4. Behaves the same as Number when converted to a boolean
const bigInt = 9007199254740993n;
console.log(typeof bigInt); // "bigint"

Ways to Create BigInt

There are three main ways to create a BigInt:

  1. Append n directly to a number
  2. Use the BigInt() constructor
  3. Use the BigInt.asIntN() and BigInt.asUintN() methods
// Method 1: Literal
const a = 123456789012345678901234567890n;

// Method 2: Constructor
const b = BigInt("12345678901234567890");

// Method 3: Bit-limited conversion
const c = BigInt.asIntN(64, 12345678901234567890n);

BigInt Operations

BigInt supports most arithmetic operators but cannot be mixed with Number types in operations:

const x = 10n;
const y = 20n;

console.log(x + y); // 30n
console.log(x * y); // 200n
console.log(y / x); // 2n (Note: BigInt division truncates the fractional part)
console.log(y % x); // 0n

// Error example
try {
  console.log(x + 10); // Throws TypeError
} catch (e) {
  console.error(e.message); // "Cannot mix BigInt and other types"
}

BigInt Comparison Operations

BigInt can be compared with Number, but type conversion must be considered:

console.log(10n == 10); // true
console.log(10n === 10); // false

console.log(10n > 5); // true
console.log(10n < 20); // true

BigInt Bitwise Operations

BigInt supports all bitwise operations, including:

const a = 0b1100n;
const b = 0b1010n;

console.log(a & b); // 0b1000n (8n)
console.log(a | b); // 0b1110n (14n)
console.log(a ^ b); // 0b0110n (6n)
console.log(~a); // -13n (bitwise NOT)

BigInt Type Conversion

BigInt can be converted to other types, but precision issues must be considered:

// Convert to boolean
console.log(Boolean(0n)); // false
console.log(Boolean(1n)); // true

// Convert to string
console.log(100n.toString()); // "100"
console.log(String(100n)); // "100"

// Convert to Number (may lose precision)
console.log(Number(9007199254740993n)); // 9007199254740992

Practical BigInt Methods

ECMAScript provides several practical BigInt methods:

// Check if it's a BigInt
console.log(typeof 100n === "bigint"); // true

// Bit limitation
const bigNum = 12345678901234567890n;
console.log(BigInt.asIntN(32, bigNum)); // -350287150n
console.log(BigInt.asUintN(32, bigNum)); // 3944680146n

BigInt Use Cases

BigInt is particularly suitable for the following scenarios:

  1. High-precision mathematical calculations
  2. Large integer ID handling
  3. Cryptographic algorithm implementation
  4. Financial calculations
// Large integer ID handling
const userId = 9007199254740993n;
console.log(`User ID: ${userId}`);

// Fibonacci sequence calculation (large number version)
function fibonacci(n) {
  let a = 0n, b = 1n;
  for (let i = 0n; i < n; i++) {
    [a, b] = [b, a + b];
  }
  return a;
}

console.log(fibonacci(100n)); // 354224848179261915075n

BigInt Considerations

When using BigInt, keep the following points in mind:

  1. JSON serialization issues
  2. Browser compatibility
  3. Performance considerations
  4. Interaction with third-party libraries
// JSON serialization issue
const obj = { id: 123n };
try {
  JSON.stringify(obj); // Throws TypeError
} catch (e) {
  console.error(e.message); // "Do not know how to serialize a BigInt"
}

// Solution: Custom serialization
const replacer = (key, value) => 
  typeof value === "bigint" ? value.toString() : value;
console.log(JSON.stringify(obj, replacer)); // {"id":"123"}

BigInt Performance Considerations

Although BigInt provides high-precision calculation capabilities, its performance is generally slower than the Number type:

// Performance test
const testCount = 1000000;

console.time("Number addition");
let numSum = 0;
for (let i = 0; i < testCount; i++) {
  numSum += i;
}
console.timeEnd("Number addition");

console.time("BigInt addition");
let bigSum = 0n;
for (let i = 0n; i < BigInt(testCount); i++) {
  bigSum += i;
}
console.timeEnd("BigInt addition");

BigInt Browser Compatibility

As of now, all modern browsers support BigInt, but older browsers may require a polyfill:

// Check if the browser supports BigInt
if (typeof BigInt === "undefined") {
  console.log("BigInt is not supported in the current environment");
  // A third-party polyfill can be used
} else {
  console.log("BigInt is supported in the current environment");
}

BigInt and TypeScript

To use BigInt in TypeScript, set target to es2020 or higher in the configuration:

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "lib": ["ES2020"]
  }
}

// Usage example
const bigInt: bigint = 123n;
console.log(bigInt * 2n);

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:动态导入

下一篇:模块命名空间导出

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.