How does the sort method decide the order of elements?
The sort method takes an optional comparison function. If you do not give it one, it compares the values as text, and that is why sorting numbers without a comparison function gives you a result that looks wrong.
The reason is simple. The default comparison turns both values into text and then compares them one character at a time. So the number ten comes before the number nine, because the text "10" comes before the text "9" when you compare the first characters.
When you do give a comparison function, the contract is easy to remember. The function receives two values and returns a negative number when the first one should come before the second one. It returns zero when the two values are treated as equal. And it returns a positive number when the first one should come after the second one. You do not have to return minus one, zero, and one exactly. Any negative number and any positive number work, and the usual shortcut is to return the difference between the two values.
Two details are worth knowing. Modern browsers keep the sort stable, which means that values your comparison function treats as equal stay in their original relative order. That matters when you sort by one field and then expect a second field to stay in place. The other detail is that sort changes the array that it is called on, which is why the newer toSorted method is often the safer choice, because it gives you a sorted copy and leaves your original array alone.