#58: '10' < '9' and localeCompare
Topic: strings · Difficulty: ★★
console.log('10' < '9');
console.log('10'.localeCompare('9'));Output
true -1
Why
The < operator on two strings compares them lexicographically, character by character, by UTF-16 code unit — never numerically, even when both strings happen to look like numbers. Comparing '10' and '9', the very first characters are '1' and '9', and '1' has a smaller code point than '9', so '10' < '9' is true, which feels wrong if you're thinking of them as the numbers ten and nine. localeCompare(), by default, performs essentially the same kind of code-unit-based ordering (without special numeric collation enabled), so '10'.localeCompare('9') also returns a negative number, confirming '10' sorts before '9' as plain text. Sorting numeric-looking strings correctly requires explicit numeric comparison or a numeric localeCompare option.