7

I have this extremely simplified code that produces opposite results in Firefox to what you get (and expect) in Chrome or Edge (haven't tried other browsers):

[1, 2, 3, 4, 5].sort((a, b) => 1).forEach(a => document.write(a));

It reverses the array in Firefox for some reason. Is this a bug or am I missing something?

Alan Mendelevich
  • 3,591
  • 4
  • 32
  • 50
  • 1
    It's not a bug, just implementation-dependent - if `1` is returned for every comparison done, then it's inconsistent, and the spec says nothing about what the results should be – CertainPerformance Mar 07 '19 at 08:29
  • why not taking `[1, 2, 3, 4, 5].sort((a, b) => a - b)` or reverse `[1, 2, 3, 4, 5].sort((a, b) => b - a)` ? – d-h-e Mar 07 '19 at 08:30
  • @CertainPerformance it's just a simplified example. It behaves the same way even if it's not the same for every comparison. Returning 1 should keep the order of 2 items unchanged, no? – Alan Mendelevich Mar 07 '19 at 08:46
  • 3
    No, a positive return value will result in `b` coming first in the result, whatever `b` is - but the spec doesn't specify which order elements are to be compared in. – CertainPerformance Mar 07 '19 at 08:50
  • @d-h-e because it's just a very simplified version of a bigger (non-numeric) example. Basically I'm doing some comparisons and wanted to avoid a separate "branch" for when both are equal. – Alan Mendelevich Mar 07 '19 at 08:50
  • @CertainPerformance ah.. makes sense. Thanks! – Alan Mendelevich Mar 07 '19 at 08:51
  • It kinda looks like a bug - what if I need a sort which sets zeros to the end of array, and keeps all meaningful items in original order, it works fine in chrome. So firefox has no way to conditionally preserve order. – lexigren Nov 11 '19 at 21:15

0 Answers0