The Default Sort Behavior
What you'll learn: How JavaScript's sort() method converts everything to strings before sorting, which can produce surprising results.
The String Conversion Surprise
When you call sort() without any arguments, JavaScript doesn't sort numbers numerically or objects logically—it converts every element to a string first, then sorts those strings in lexicographic order (dictionary order based on Unicode character values).
This means sort() compares elements character-by-character from left to right, just like words in a dictionary:
const words = ['banana', 'apple', 'cherry'];
words.sort();
console.log(words); // ['apple', 'banana', 'cherry'] ✓ Works as expected
Where It Gets Weird: Numbers
Here's where default sort behavior catches beginners off-guard:
const numbers = [10, 2, 30, 1, 200];
numbers.sort();
console.log(numbers); // [1, 10, 2, 200, 30] ⚠️ Surprising!
Why? Because JavaScript converted everything to strings first: "10", "2", "30", "1", "200". In lexicographic order, "10" comes before "2" because the character "1" comes before "2" in Unicode.
The Dictionary Analogy
Think of how a dictionary works: "Apple" comes before "Banana" even though both start with capital letters. Similarly, "10" comes before "2" because we're comparing the first characters: "1" vs "2".
Why This Design?
JavaScript's default behavior prioritizes flexibility over assumptions. Since arrays can contain mixed types, string conversion provides a universal (if imperfect) comparison method. That's why you need comparator functions to sort numbers correctly.
Key Takeaway: Array.prototype.sort() converts all elements to strings and sorts lexicographically by default—this works great for strings but produces unexpected results for numbers without a custom comparator function.