JavaScript .sort() is broken

I am currently playing with Node.js and started to do some code challenges in JavaScript.
In one of these challenges, an array is given and it asks for the smallest number, for example:


arr = [85, -572, -1, 99]
arr.sort()
=> [-1, -572, 85, 99]

WHAT!?

In ruby

arr = [85, -572, -1, 99]
arr.sort
=> [-572, -1, 85, 99]

In Python (called lists)


arr = [85, -572, -1, 99]
arr.sort
=> [-572, -1, 85, 99]

In Erlang (uses lists)


List = [85, -572, -1, 99]
lists:sort(List).
=> [-572,-1,85,99]

As you can see, these languages sort properly. You just need to get the first position on the array or list and the challenge is done.
After a bit of documentation research I found out that you have to pass a function as an argument to the .sort() to compare the numeric values.


compareNumbers = function(a, b) {
  return a - b;
}


arr.sort(compareNumbers)
=> [-572, -1, 85, 99]

I just prefer to do this way:

arr.sort((a, b) => a - b)

OR

Math.min(...arr)

Leave a comment