-2
const n = [2, 5, 100, 4]

n.sort((a, b) => {
 console.log(a, b)
 return a - b;
})

// console log
5 2
100 5
4 100

Why is a 5 and b 2, etc..?

In this question which asks a similar question.

Answers given amount to: "Browsers interpret the spec, therefore the order is not guaranteed". But fails to answer the question.

GN.
  • 8,672
  • 10
  • 61
  • 126
  • clearly sort callback is called that way - does it matter? note: firefox calls with the arguments in your "expected" order - yet the result is the same, the internal workings are different, so, it doesn't matter – Bravo Sep 22 '21 at 05:08
  • sorry - does this answer your question? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Mohammad Mostafa Dastjerdi Sep 22 '21 at 05:10
  • @MMD - that shows no reference to how the sort function is called and in what order the values are sent - because the implementation doesn't matter – Bravo Sep 22 '21 at 05:11
  • the sent values doesn't matter - you just need to tell it between the two given, which one is greater. – Mohammad Mostafa Dastjerdi Sep 22 '21 at 05:15
  • From the [specification](//tc39.es/ecma262/#sec-array.prototype.sort): _“Step 8: Sort items using an **implementation-defined** sequence of calls to SortCompare.”, “The abstract operation SortCompare takes arguments_ x _and_ y. _It also has access to the_ comparefn _argument passed to the current invocation of the `sort` method.”_ (emphasis mine). – Sebastian Simon Sep 22 '21 at 05:19
  • What more do you want? If you want to learn why a browser vendor implemented this in a certain way, go ask the maintainers or read the open source code of the browser. This is either too opinion-based or too broad for Stack Overflow. – Sebastian Simon Sep 22 '21 at 05:52

1 Answers1

0

The standard 22.1.3.27 does not specify how the compare function is being called:

Perform an implementation-dependent sequence of calls to the [[Get]] and [[Set]] internal methods of obj, to the DeletePropertyOrThrow and HasOwnProperty abstract operation with obj as the first argument, and to SortCompare (described below)

Allan Wind
  • 23,068
  • 5
  • 28
  • 38