Last updated: October 7, 2021.
With ECMAScript 2020, a seventh primitive type was introduced to the language to the language,
In this article, we will cover all you need to know about BigInt: Why we need it, how to create it and features of working with it.
Let’s get started!
Why we need BigInt
Number type isn’t perfect at handling very large numbers with precision.
In fact, by calling
Number.MAX_SAFE_INTEGER, we can see the largest integer that it is safe to work with when working with
alert(Number.MAX_SAFE_INTEGER); // 9007199254740991
This implies that working with numbers in excess of this is ‘unsafe’. What do we mean?
Concretely, we can work with an integer of type
Number up until 9007199254740991 with guaranteed precision. But working with numbers greater than this risks losing precision.
For example, if we try to alert the number
99999999999999999 as a
Number type, you can clearly see the problem:
alert(99999999999999999); // 100000000000000000
This makes exact calculations with very large numbers problematic when using the
Number type. It can also be a problem if the number is long but needs to be exact, such as an identification or serial number.
BigInt enables us to work with larger numbers without losing any precision.
Creating a BigInt
The first way to create a BigInt integer is to call the object directly. For example:
const largeNumber = BigInt("99999999999999999"); console.log(largeNumber); // 99999999999999999n console.log(typeof largeNumber); // bigint
A more convenient method is to simply place
n after a number:
const largeNumber = 99999999999999999n; console.log(largeNumber); // 99999999999999999n console.log(typeof largeNumber), // bigint
BigInt can handle smaller numbers to, just like
const x = BigInt("2"); console.log(x); // 2n
n is returned after the interger.
const x = BigInt("2"); const y = 2 console.log(x + y); // Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
If we want to make such a calculation, we can by convert the
Number to a
BigInt by passing it inside
const x = BigInt("2"); const y = 2; console.log(x + BigInt(y)); // 4n
Or, by converting the
BigInt value to a
Number type by passing it through
const x = BigInt("2"); const y = 2; console.log(Number(x) + y); // 4
When making comparisons, if BigInt and Number contain the same value, they are considered equal (
==) but not strictly equal (
const x = BigInt("2"); const y = 2; alert(x==y); // true alert(x===y); // false
In this article, we have seen why we need BigInt, how to create one and its most important features.
It is not a primitive data type that you will use anywhere near as much as Number, String or Boolean. However, it is a welcome addition that increases the reliability of the language.