Temp O'rary
Temp O'rary

Reputation: 5828

What are the arguments of "compareFunction" in sort of Array in JavaScript?

What are the arguments of "compareFunction" in sort of Array in JavaScript? If you notice the second argument, it comes in randomly not in any particular order. Whereas the first argument is always in the current order. I want to know how is the second argument choosen.

arr.sort(compareFunction)

Upvotes: 1

Views: 141

Answers (1)

Pointy
Pointy

Reputation: 413836

You can make no assumptions at all about how or why the sort mechanism passes parameters. It's not in the specification, and the JavaScript runtime is free to implement the sort any way it wants. It's not even required that the same sort mechanism be used in all cases.

The comparator function should simply compare the two elements and return a numeric result. Furthermore, a proper comparison function should be consistent: for any pair of elements (in either order), the result of calling the comparison function should reflect the same ordering. The function should be transitively consistent as well. The comparison function should not make any changes to the list being sorted. If the comparison function does not satisfy those conditions, the result of the sort operation is implementation-defined (ie, you can't rely on any particular result).

Upvotes: 3

Related Questions