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

Comparing Different Types

Learn how comparison operators handle mixed types and when coercion occurs with < and >.

Comparing Different Types

You'll learn how JavaScript's comparison operators behave when you compare values of different types.

The Core Idea

When you use <, >, <=, or >= to compare values of different types (like a number and a string), JavaScript tries to convert them to numbers first before comparing. This automatic conversion is called type coercion.

This is different from == and ===, which have their own coercion rules. With relational operators (<, >), JavaScript almost always attempts numeric conversion.

How It Works

5 > "3"        // true (string "3" becomes number 3)
10 < "20"      // true (string "20" becomes number 20)
"100" > 50     // true (string "100" becomes number 100)

Both values get coerced to numbers, then the comparison happens numerically.

When Things Get Tricky

5 > "apple"    // false (because "apple" becomes NaN, and any comparison with NaN is false)
10 < "banana"  // false (same reason)
NaN >= NaN     // false (NaN is never equal to or greater/less than anything, even itself)

When a string can't be converted to a valid number, it becomes NaN, and comparisons with NaN always return false.

Think of It Like This

Imagine two people speaking different languages trying to compare heights. JavaScript acts as a translator, converting both measurements to the same unit (numbers) before comparing. But if one measurement is gibberish, the comparison fails.

Key Takeaway: Relational operators (<, >, <=, >=) coerce both sides to numbers before comparing, which can lead to unexpected results when mixing types—especially with non-numeric strings that become NaN.