Numbers are an essential part of any software application. In the world of JavaScript—the dynamic language that powers the web—understanding how to work with numbers is crucial. It goes far beyond simple arithmetic, encompassing precision with decimals, managing large integers, and dealing with special numeric cases.
In this comprehensive guide, we'll explore everything you need to know to handle numbers in JavaScript like a pro—helping you write robust, efficient, and error-free code.
Number
Data TypeUnlike other programming languages that distinguish between integers and floats, JavaScript simplifies things by offering a single numeric type: Number
. All numbers, whether integers like 100
or decimals like 25.5
, are represented using the double-precision floating-point format, based on the
IEEE 754 standard.
let integerNumber = 150; // Integer
let decimalNumber = 3.14; // Decimal
let largeNumber = 2.99e8; // Equals 299000000
let smallNumber = 1.6e-19; // Equals 0.00000000000000000016
During calculations, you may encounter certain special values with specific meanings:
Infinity
and -Infinity
: Represent positive and negative infinity, such as division by zero or overflow.NaN
(Not a Number): Returned when an invalid math operation occurs. Use isNaN()
to test for it.BigInt
JavaScript’s BigInt
type allows you to work with integers beyond the Number.MAX_SAFE_INTEGER
limit.
// Using the "n" suffix
const massiveNumber = 1234567890123456789012345678901234567890n;
// Using the constructor
const anotherMassiveNumber = BigInt("987654321098765432109876543210");
// Avoid mixing BigInt and Number
let bigIntNum = 100n;
let regularNum = 10;
// Error: let result = bigIntNum + regularNum;
// Correct usage
let correctResult = bigIntNum + BigInt(regularNum); // 110n
Learn more from the official MDN Web Docs on BigInt.
Use built-in methods to convert between strings and numbers:
let strInt = "42";
let strFloat = "3.14159";
let intValue = parseInt(strInt, 10); // 42
let floatValue = parseFloat(strFloat); // 3.14159
let num = 255;
let binaryString = num.toString(2); // "11111111"
let hexString = num.toString(16); // "ff"
new Number()
: It creates an object instead of a primitive, which can lead to performance issues and bugs.BigInt
for large integers: Especially when precision matters above the safe integer range.Number.EPSILON
to compare decimals reliably.isNaN()
before performing calculations.JavaScript’s number system—through Number
and BigInt
—equips you with powerful tools to manage numerical data efficiently. By mastering type conversions, avoiding common pitfalls, and applying best practices, you'll write cleaner and more reliable code. This knowledge is a core milestone on your journey to becoming a professional JavaScript developer.