What is a Number?
Numbers are everywhere in JavaScript: from simple counters and prices to complex calculations and data analysis. In JavaScript, numbers are a single primitive type—there is no separate int or float as in some other languages. All numbers, whether whole or decimal, positive or negative, are represented using the IEEE 754 double-precision floating-point format.
let age = 25; // integer
let price = 19.99; // floating-point
let big = 2e6; // exponential notation (2,000,000)This means you can use numbers flexibly, but it also means you need to be aware of some quirks and limitations.
Number Types in JavaScript
JavaScript numbers can be:
- Integers (e.g.,
42,-7) - Floating-point numbers (e.g.,
3.14,-0.001) - Special values:
Infinity,-Infinity, andNaN(Not-a-Number)
console.log(1/0); // Infinity
console.log(-1/0); // -Infinity
console.log(0/0); // NaNInfinity and -Infinity are returned when a number exceeds the largest (or smallest) representable value. NaN is the result of an invalid mathematical operation, such as dividing zero by zero or parsing a non-numeric string.
NaN in JavaScript: Not-a-Number Explained
NaN stands for "Not-a-Number" and is a special value in JavaScript that represents the result of an invalid or undefined mathematical operation. NaN is still of type number (which is a common source of confusion!).
Common ways to get NaN:
- Dividing zero by zero:
0/0 - Parsing a non-numeric string:
parseInt("hello") - Math operations with undefined or non-numeric values:
Math.sqrt(-1),undefined + 1
console.log(0/0); // NaN
console.log(parseInt("hello")); // NaN
console.log(Math.sqrt(-1)); // NaN
console.log(undefined + 1); // NaNChecking for NaN: Use isNaN() to check if a value is NaN. But beware: isNaN() first tries to convert the value to a number, so isNaN("abc") is true (because Number("abc") is NaN).
console.log(isNaN(NaN)); // true
console.log(isNaN("abc")); // true
console.log(isNaN(42)); // falseFor a stricter check, use Number.isNaN() (ES6+), which only returns true if the value is actually NaN:
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("abc")); // false
console.log(Number.isNaN(0/0)); // trueQuirks of NaN:
typeof NaNis"number"- NaN is not equal to itself:
NaN === NaNisfalse - To check if a value is NaN, never use
===; always useisNaN()orNumber.isNaN()
console.log(typeof NaN); // "number"
console.log(NaN === NaN); // false
console.log(isNaN(NaN)); // truePractical tip: Always validate user input and check for NaN before performing calculations, especially when parsing numbers from strings or external sources.
Number Pitfalls: Precision and Comparisons
Because JavaScript uses floating-point arithmetic, you may encounter unexpected results:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.7); // 0.7999999999999999
console.log(0.1 + 0.2 === 0.3); // falseThis is not a bug in JavaScript, but a limitation of binary floating-point math. When comparing decimals, use a tolerance:
function nearlyEqual(a, b, epsilon = 1e-10) {
return Math.abs(a - b) < epsilon;
}
console.log(nearlyEqual(0.1 + 0.2, 0.3)); // trueNumber Methods and Properties
JavaScript provides several useful methods and properties for working with numbers:
- toFixed(n): Formats a number using fixed-point notation (useful for currency).
- toPrecision(n): Formats a number to a specified length.
- toString([radix]): Converts a number to a string, optionally in a different base (binary, hex, etc.).
- toExponential(n): Returns a string with a number in exponential notation.
- valueOf(): Returns the primitive value of a number object. Useful when you have a Number object (created with
new Number()) and want to get its underlying numeric value.
let n = 123.456;
console.log(n.toFixed(1)); // "123.5"
console.log(n.toPrecision(4)); // "123.5"
console.log(n.toString(2)); // "1111011" (binary)
console.log(n.toExponential(2)); // "1.23e+2"
// valueOf example:
let numObj = new Number(42);
console.log(typeof numObj); // "object"
console.log(numObj.valueOf()); // 42 (primitive number)
let numPrim = 42;
console.log(numPrim.valueOf()); // 42 (primitive, so returns itself)
Parsing and Converting Numbers
Often, you need to convert strings to numbers (e.g., from user input or APIs). JavaScript provides several ways:
- parseInt(string, [radix]): Parses a string and returns an integer.
- parseFloat(string): Parses a string and returns a floating-point number.
- Number(value): Converts a value to a number (returns
NaNif not possible).
console.log(parseInt("42")); // 42
console.log(parseFloat("3.14")); // 3.14
console.log(Number("123")); // 123
console.log(Number("abc")); // NaNTip: Always check for NaN when parsing user input.
The Math Object: Your Numeric Toolbox
The Math object is a treasure trove of mathematical functions and constants. Here are some essentials:
- Math.PI: The value of π (3.14159...)
- Math.round(x): Rounds to the nearest integer
- Math.floor(x): Rounds down
- Math.ceil(x): Rounds up
- Math.abs(x): Absolute value
- Math.max(...args): Maximum value
- Math.min(...args): Minimum value
- Math.random(): Random number between 0 and 1
- Math.pow(x, y): Exponentiation
- Math.sqrt(x): Square root
console.log(Math.PI); // 3.141592653589793
console.log(Math.round(3.7)); // 4
console.log(Math.floor(3.7)); // 3
console.log(Math.ceil(3.1)); // 4
console.log(Math.abs(-5)); // 5
console.log(Math.max(1, 2, 3)); // 3
console.log(Math.min(1, 2, 3)); // 1
console.log(Math.random()); // random number between 0 and 1
console.log(Math.pow(2, 3)); // 8
console.log(Math.sqrt(16)); // 4Best Practices for Working with Numbers
- Use
Number()for conversion when you expect a number, butparseInt()orparseFloat()for parsing user input. - Always check for
NaNusingisNaN()before calculations. - Be careful with floating-point precision—avoid direct equality checks for decimals.
- Use
Math.round(),Math.floor(), andMath.ceil()for rounding. - Use
toFixed()for formatting decimals for display (e.g., currency). - Remember that
typeof NaNis"number"(quirk of JavaScript).
Key Takeaways
Numbers are a core part of JavaScript. Mastering them means you can handle everything from simple counters to complex financial calculations. Always be aware of floating-point quirks, use the right methods for parsing and formatting, and leverage the Math object for advanced operations.