Array.prototype.sort() doesn't work well with boolean


Array.prototype.sort() doesn't work well with boolean

Currently I got two user reports on sorting issue in my Owl Reminder app. It looks strange as it was definitely working before. I looked into my code and found I was using Array.prototype.sort() and it was feeding a boolean type:

$scope.eventArray = eventArray.sort(function (a, b) {
  return new Date(a.startTime) > new Date(b.startTime);

However according to ECMAScript, the comparsion function in sort should be given a real value, not a binary boolean.

Array.prototype.sort (comparefn)

The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.

What happen if I use boolean instead? People already discuss this kind of issue on StackOverflow:

Because the exact sorting algorithm is browser dependent and is not necessarily stable, returning boolean for sort() can be dangerous as there are only two values. 0 can be either less than or equal to. In a stable naive algorithm like bubble sort, boolean type is probably all right, no side-effects of treating two cases as the same. For some more efficient unstable sort, this can cause serious issue. This might explain why sorting was working for some older version of Chrome but a new version breaks it.