The latest ES2020 defines nine data types. Six data types that are primitives, checked by the typeof operator, null, Object and Function. Primitives are undefined, Boolean, Number, String, Symbol and the new one is BigInt. For the first time in JavaScript we can store numbers bigger than a Number, in other words, store whole numbers larger than 253 - 1.
We can create a BigInt by appending n at the end of an integer or with the constructor BigInt()
const big = 12345n;
typeof big; // "bigint"
const sameBig = BigInt("12345"); //12345n
const oneMoreSame = BigInt(12345); //12345n
Operations with BigInt
Operations like +, *, -, **, % can be used just like with Numbers.
const huge = 20n + 4n; //24n
const oneMore = 20n - 4n; //16n
const oneBig = 20n ** 4n; //160000n
Bitwise operators can also be used, except >>> (zero-fill right shift) as all BigInts are signed.
const big = 20n & 4n; //4n
We need to keep in mind that the result of / operation will round toward 0 like for any other Number.
const big = 20n / 4n; //5n
const huge = 20n / 3n; //6n
The unary + is not supported.
const big = +3n; //Error: Cannot convert a BigInt value to a number
Comparison and operations with other types
You can’t mix BigInt with other types, not even Numbers. Something like this would give you an error.
const big = 20n + 4; //Error: Cannot mix BigInt and other types
But we can convert them.
const big = 20n + BigInt(4); //24n
const huge = Number(20n) + 4; //24
With a String, the BigInt can be concatenated.
const big = 20n + "4"; //"204"
BigInt is loosely equal to a Number but it is not strictly equal.
20n == 20; //true
20n === 20; //false
The Number and BigInt data types can be compared naturally.
20 > 10n; //true
20n >= 20; // true
We can see the similarity between Number and BigInt but one important thing is that it can not be used with methods in the built-in Math object. On the other hand, BigInt behaves like a Number when used with logical operators (||, &&, !), when is converted to a Boolean and within a conditional test.
const big = Boolean(20n); //true
!big; //false
Conclusion
Along with the nullish coalescing operator and the optional chaining operator that we already wrote about it, BigInt is right now in stage 4, the final stage of ECMAScript standard. In the official proposal we can see that it has been shipped in Chrome, Node, Firefox, and is underway in Safari.