Guide to Basic Understanding of BigInt

A Brief Introduction to BigInt

Serkan Sahin
3 min readJan 28, 2021

Intro

In JavaScript, the Number data type cannot safely represent integer values larger than 2⁵³-1. The MAX_SAFE_INTEGER constant has a value of 900719925470991. Safe means that you have the ability to represent integers exactly and thus giving you the capability to compare them to other numbers, operate on those integers, and more! So, anything past the max safe integer, is no longer reliable and accurate information.

You can see how this can force developers to use inefficient workarounds and third party libraries. Thats where BigInt comes in. Big Int is a new data type created to fix that.

What is BigInt?

Prior to 2020, there were officially only 6 Javascript primitive data types:

In June of 2019, Daniel Ehrenberg, authored BigInt and it was officially accepted through a stage 4 proposal in ECMA-262. With the introduction of BigInt, JavaScript now has a new primitive datatype that allows representing numbers larger than 2⁵³, which is the largest number JavaScript can reliably represent.

How to create a BigInt

You can create a BigInt by simply appending n to the end of an integer or by using the BigInt constructor — BigInt() .

Operators

Operators that may be used with BigInts include:

  • Addition ( + )
  • Subtraction (-)
  • Multiplication ( * )
  • Division (/) (will round down)
  • Exponentiation (**)
  • Modulus(%)
  • Bitwise Operators(~, &, ||)

So what can’t we use it with? Only unary operators are not capable of using BigInt. Such as (++) and (- -). Since these are BigInts and not BigDecimals, division operation will round towards 0. Also, don’t mix up the Number and BigInt datatype and remember to convert.

Implicit Type Conversion

It’s not possible to perform math operations with a mix of Number and BigInt integers. You can simply convert a Number to a BigInt or vice versa by calling BigInt() or Number().

Browser Support

Currently, BigInt is supported by all up-to-date browsers except Internet Explorer and Opera. You can use https://caniuse.com/ to test your features for compatibility across browsers and devices.

Conclusion

You might not have to use BigInt muchBigInt is a new datatype intended to be used when integer values are larger than the range supported by the Number data type. This data type allows us to safely perform arithmetic operations on large integers, use large integer IDs, and more without the need to use a third party library. Remember to not use operations with a mix of Number and BigInt datatypes. Make sure to convert one integer to the other datatype and remember also that unary operators will not work on BigInt.

Resources

--

--