JSBI: Pure JavaScript BigInt Implementation

4.3.2 · active · verified Sun Apr 19

JSBI (JavaScript BigInt) is a pure-JavaScript implementation of the ECMAScript BigInt proposal, which officially became a part of the JavaScript language in ES2020. The current stable version is 4.3.2. This library serves as a robust polyfill, enabling developers to use arbitrary-precision integers in JavaScript environments that lack native BigInt support, such as older browsers and Node.js versions. A key differentiator of JSBI is its precise adherence to the native BigInt specification's behavior, which facilitates a straightforward, mechanical migration path to native BigInts once they are universally supported, often accomplished through the `babel-plugin-transform-jsbi-to-bigint` plugin. JSBI prioritizes performance, aiming to be highly competitive with native BigInt implementations. Its release cadence is primarily driven by maintenance requirements and alignment with ECMAScript specification updates, rather than frequent feature additions, given its role as a specification-compliant polyfill.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to import JSBI, create BigInt instances from numbers and strings, and perform arithmetic operations like addition and multiplication using JSBI's static methods, mimicking native BigInt behavior.

import JSBI from 'jsbi';

function demonstrateJSBI() {
  // Install: npm install jsbi

  const maxSafeInteger = Number.MAX_SAFE_INTEGER;
  console.log(`Max safe integer (JS Number): ${maxSafeInteger}`);

  // Create JSBI instances from numbers or strings
  const max = JSBI.BigInt(maxSafeInteger);
  console.log(`JSBI equivalent of MAX_SAFE_INTEGER: ${String(max)}`); // Use String() for clear output

  const other = JSBI.BigInt('2');
  console.log(`Another JSBI instance: ${String(other)}`);

  // Perform addition using JSBI's static methods, as native operators are not overloaded
  const result = JSBI.add(max, other);
  console.log(`Result of JSBI.add(${String(max)}, ${String(other)}): ${String(result)}`);

  // Demonstrate arithmetic beyond Number.MAX_SAFE_INTEGER
  const largeNumber = JSBI.BigInt("9007199999999999");
  const anotherLargeNumber = JSBI.BigInt("12345678901234567890");
  const product = JSBI.multiply(largeNumber, anotherLargeNumber);
  console.log(`Product of two large JSBI numbers: ${String(product)}`);

  // Comparison operations
  const isGreater = JSBI.greaterThan(product, JSBI.BigInt(0));
  console.log(`Is the product greater than 0? ${isGreater}`);
}

demonstrateJSBI();

view raw JSON →