In JavaScript, the standard Number data type is a 64-bit floating-point value. While this works perfectly for most applications, it has a strict limit on how large (or small) an integer can safely be represented.
The safe limits of the standard number data type are between 2⁵³ - 1 (9007199254740991) and -(2⁵³ - 1) (-9007199254740991).
In case you ever need to work with a bigger (or smaller) integer that exceeds these boundaries, the BigInt data type comes into play.
A BigInt data type can be easily recognized by the postfix n added to the end of an integer literal.
// A standard Number let intNr = 9007199254740991;// A BigInt (notice the 'n' at the end) let bigNr = 90071992547409920n;
console.log(typeof intNr); // "number" console.log(typeof bigNr); // "bigint"
You can perform standard mathematical operations (like addition, subtraction, multiplication) on BigInt values, just like you would with regular numbers.
However, you must be extremely careful when mixing BigInt with the standard Number type. Let's see what happens when we try to do a calculation between our previously made integer intNr and the BigInt bigNr:
let intNr = 10; let bigNr = 90071992547409920n;// Attempting to add a Number and a BigInt let result = bigNr + intNr;
If you run the code above, the output will be as follows:
Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
Uh-oh, a TypeError! JavaScript is very clear about what is going wrong here. We cannot mix BigInt with the standard Number data type to perform operations.
This is a crucial rule to keep in mind when working with BigInt—you can only operate on a BigInt with other BigInt values.
If you absolutely must perform math using both a BigInt and a regular Number, you need to use explicit conversion. You can convert the Number to a BigInt using the BigInt() function.
let intNr = 10; let bigNr = 90071992547409920n;// Convert intNr to a BigInt before adding let result = bigNr + BigInt(intNr);
console.log(result); // 90071992547409930n
What happens if you try to add a BigInt and a regular Number together without converting them first?