I think MDN has Explained it well Source MDN Array.sort()
The sort() method sorts the elements of an array in place and returns
the array. The sort is not necessarily stable. The default sort order
is according to string Unicode code points.
arr.sort([compareFunction])
compareFunction Optional
- Specifies a function that defines the sort order. If omitted, the
array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
- If compareFunction is not supplied, elements are sorted by converting
them to strings and comparing strings in Unicode code point order. For
example, "Cherry" comes before "banana". In a numeric sort, 9 comes
before 80, but because numbers are converted to strings, "80" comes
before "9" in Unicode order.
var scores = [1, 10, 2, 21];
scores.sort(); // [1, 10, 2, 21]
// Watch out that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
To compare numbers instead of strings, the compare function can simply
subtract b from a. The following function will sort the array
ascending:
function compareNumbers(a, b) {
return a - b;
}
Example:
function compareNumbers(a, b) {
return a - b;
}
var scores = ['1', '010', '200', '110'];
scores.sort(compareNumbers);
O/P: Array [ "1", "010", "110", "200" ]