String Sorting and Locale-Aware Comparison
You'll learn why simple string comparison fails for international text and how to sort strings properly across languages.
When you compare strings in JavaScript using operators like < or >, JavaScript compares Unicode code points numerically. This works fine for basic ASCII characters ('a' < 'b' returns true), but breaks down spectacularly with accented characters, special alphabets, or locale-specific sorting rules.
For example, in Swedish, 'ö' comes after 'z' in the alphabet, but 'ö' < 'z' returns false in JavaScript because ö has a higher Unicode value. Similarly, 'ä' < 'b' returns false, even though ä comes before b in Swedish sorting.
The Problem with Default Sorting
const words = ['äpple', 'banana', 'zebra', 'öga'];
console.log(words.sort());
// ['banana', 'zebra', 'äpple', 'öga'] ❌ Wrong for Swedish!
Enter Intl.Collator
Intl.Collator provides locale-aware string comparison that respects cultural sorting rules. It knows that in German, 'ä' sorts near 'a', while in Swedish it sorts near the end of the alphabet.
const swedishCollator = new Intl.Collator('sv');
const words = ['äpple', 'banana', 'zebra', 'öga'];
console.log(words.sort(swedishCollator.compare));
// ['banana', 'zebra', 'äpple', 'öga'] ✓ Correct for Swedish!
Think of Intl.Collator as a cultural translator for your sort function—it understands that alphabetical order isn't universal.
Key Takeaway: Never use plain <, >, or default sort() for user-facing text that might contain non-ASCII characters; always use Intl.Collator with the appropriate locale for culturally correct string comparison and sorting.