Modern Math (ES6+)
Overview
Modern JavaScript (ES6 and beyond) introduced several crucial enhancements to handle edge-cases in mathematics, primarily through the global Number object and the new BigInt primitive type.
Historically, JavaScript only had one number type: a 64-bit float. This meant it could not accurately represent integers larger than 9,007,199,254,740,991. BigInt solves this. Furthermore, robust type-checking methods were added to the Number object.
Syntax
// Safer than the global isNaN() which forces type coercion
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("hello")); // false
// Checking for finite numbers (not Infinity or NaN)
console.log(Number.isFinite(10 / 0)); // false (Infinity)
// Checking for integers
console.log(Number.isInteger(10.5)); // false
console.log(Number.isInteger(10)); // true// The maximum safe integer in standard JS
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
// Create a BigInt by appending 'n' to the end of an integer
const massiveNumber = 90071992547409912345n;
const anotherBigInt = BigInt("90071992547409912345");
console.log(massiveNumber + 10n);Common Pitfalls
- You cannot mix
BigIntand standardNumbertypes in arithmetic operations.10n + 5will throw a TypeError. You must explicitly convert one of them:10n + BigInt(5).
Interview Questions
isNaN() and Number.isNaN()?Global isNaN() first coerces the value to a Number. So isNaN('hello') is true. Number.isNaN() does NOT coerce types. It only returns true if the value is strictly the NaN value. Number.isNaN('hello') is false.
Real-World Example
Working with massive database IDs (like Twitter Snowflakes) which exceed the 64-bit float limit. Without BigInt, JS rounds the IDs, causing catastrophic data corruption.
const tweetId = 1489033324908470275n;
console.log(tweetId.toString());Check Your Knowledge
Test your understanding of Modern Math (ES6+) with these quick questions.