Course contentsShow
← JavaScript
Lesson 295 of 2,7238. Type CoercionFree lesson

Comparison Coercion with Mixed Types

Why '10' > 9 is true but '10' > '9' is false, and how > triggers ToNumber on both sides.

Comparison Coercion with Mixed Types

What you'll learn: Why comparing a string to a number using > or < doesn't work the same as comparing two strings.

When you use comparison operators like >, <, >=, or <= with mixed types, JavaScript applies ToNumber coercion to both operands before comparing them. This creates surprising behavior when you're not expecting it.

The Classic Example

'10' > 9    // true
'10' > '9'  // false

Why the difference?

In the first comparison ('10' > 9), you're mixing types: a string and a number. JavaScript says "I need to compare these as numbers," so it converts both sides using ToNumber. The string '10' becomes the number 10, and 10 > 9 is clearly true.

In the second comparison ('10' > '9'), both sides are strings. When both operands are already strings, JavaScript skips numeric conversion entirely and does lexicographic (dictionary-style) comparison instead. It compares character by character: '1' comes before '9' in Unicode order, so '10' is considered "less than" '9' alphabetically.

The Rule

The >, <, >=, and <= operators trigger ToNumber on both sides when types don't match. If both are already strings, it stays in string-comparison mode.

'100' > 20   // true (100 > 20)
'100' > '20' // false ('1' < '2' in dictionary order)

Key Takeaway: Comparison operators with mixed types coerce both sides to numbers, but when comparing two strings, JavaScript uses alphabetical ordering instead—leading to very different results.