Recently when I was working with JavaScript \"sort()\" function, I found in one of the tutorials that this function does not sort the numbers properly. Instead to sort numbe
The problem lies with the use of strings to represent numbers, which the sort function unfortunately does as default. Strings are sorted alphabetically. The comparison function in your code just forces the strings to be evaluated as numbers.
I'd consider it very bad API design that the sort function defaults to treating the elements as strings, but it may be necessary given JavaScript's loose type system..