Course contentsShow
← JavaScript
Lesson 64 of 2,7232. Values and TypesFree lesson

String and Number Comparisons

See how strings are compared lexicographically and how numbers follow numeric ordering rules.

String and Number Comparisons

You'll learn: How JavaScript compares strings alphabetically and numbers numerically, and why they follow different rules.

Two Different Comparison Systems

When you use relational operators like <, >, <=, and >=, JavaScript applies different logic depending on whether you're comparing strings or numbers.

Number Comparisons: Straightforward Math

Numbers compare exactly as you'd expect from mathematics:

console.log(5 < 10);    // true
console.log(100 > 50);  // true
console.log(-3 < 0);    // true

String Comparisons: Dictionary Order

Strings compare lexicographically—essentially, dictionary order based on character codes. JavaScript compares character-by-character from left to right:

console.log('apple' < 'banana');  // true (a comes before b)
console.log('cat' > 'car');       // true (t comes after r)
console.log('10' < '9');          // true (!!)

Why is '10' < '9' true? Because as strings, they're compared character-by-character. The character '1' comes before '9' in the character code table, so '10' is "smaller."

The Gotcha: Mixing Types

If you compare a string and a number with < or >, JavaScript attempts to convert the string to a number first:

console.log('50' < 100);  // true (converts '50' to 50)
console.log('apple' < 5); // false (NaN comparison)

Key Takeaway: Numbers compare numerically as expected, but strings compare character-by-character in dictionary order—which can produce surprising results like '10' < '9' being true. Always be mindful of your value types when comparing.