Course contentsShow
← JavaScript
Lesson 208 of 2,7236. Booleans and ConditionalsFree lesson

Comparing Numbers

Explore how numeric comparisons work, including special cases like NaN, Infinity, and -0.

Comparing Numbers

You'll learn how numeric comparisons behave in JavaScript, including tricky edge cases with special values.

The Core Idea

When you compare two numbers using operators like <, >, <=, or >=, JavaScript follows straightforward mathematical rules—mostly. Regular numbers compare as you'd expect: 5 > 3 is true, 10 <= 10 is true. But JavaScript has special numeric values that behave differently: NaN, Infinity, -Infinity, and even -0.

How Comparisons Work

For normal numbers, comparisons work intuitively:

42 > 20;        // true
15 < 15;        // false
15 <= 15;       // true
-5 > -10;       // true (closer to zero is greater)

Special Cases to Watch

NaN breaks all comparisons. Any comparison involving NaN returns false, even NaN === NaN:

NaN > 5;        // false
NaN < 5;        // false
NaN >= NaN;     // false (!)

Infinity behaves mathematically:

Infinity > 1000000;     // true
-Infinity < -1000000;   // true
Infinity > -Infinity;   // true

Signed zero (-0) compares equal to positive zero:

-0 === 0;       // true
-0 < 0;         // false
-0 <= 0;        // true

Think of number comparisons like judging positions on a number line—except NaN refuses to stand on the line at all, and both zeros occupy the same spot.

Key Takeaway: Number comparisons follow math rules for regular numbers, but NaN always returns false in comparisons, Infinity acts as the largest/smallest value, and -0 equals 0 in all comparisons.