-3

You can see literraly everywhere(youtube, articles) that the "a" and "b" parameters of the js sort method correspond to respectively the first and second element of the array. That's wrong, take a look :

const numbers = [3,2,1];

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

The console looks like this :

2 3
1 2
[1, 2, 3]

We clearly see that the values of "a" and "b" in the first execution of the callback are 2 and 3. This is against all logics aha !

Don't get me wrong I completely understood this function and the sorting algorithm beneath it, but why "a" is not equal to the first element of the array ? :)

And why there are tons of articles and youtube videos saying that "a" is equal to the first element of the array which is actually not true at all ?

J.doe
  • 115
  • 10
  • The sorting algorithm used by `Array#sort` is completely implementation-dependent. Hence, all calls made to the callback can also differ in different JS engines. – FZs Apr 01 '21 at 09:52
  • 1
    "*You can see literraly everywhere that the "a" and "b" parameters of the js sort method correspond to respectively the first and second element of the array.*" - uh, that's completely wrong. The comparison function compares *arbitrary* values from anywhere in the array, and *different* values on every invocation (the argument `1` to in the second call is neither the first nor second value in the array at all). Can you link some videos/articles as examples please? – Bergi Apr 01 '21 at 10:05

1 Answers1

0

And why there are tons of articles and youtube videos saying that "a" is equal to the first element of the array

Well this is why we shouldn't believe everything we read or see. The actual documented details of how the browser should implement sort don't mention this. In fact it states:

Sort items using an implementation-defined sequence of calls to SortCompare.

So it's entirely up to the browser how this should be implemented. Ultimately the result is the same so I can't really see why this matters.

Liam
  • 27,717
  • 28
  • 128
  • 190
  • Thank you for your resonse, so it's up to the browser. Well the problem is that all youtubers / blog writers are saying that a = first el of array, which is not true, and you can't build a website or a software with false assomptions, even if the result is correct right ? It leads to a global missunderstanding and sooner or later, many bugs. – J.doe Apr 01 '21 at 10:09
  • 1
    Well you need to get your information from truted sources. I could stick up a you tube video saying anything, doesn't make it true. The link goes to [Tc39](https://tc39.es/) who are a **trusted source** on the actual W3c specs. Another good one is [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). – Liam Apr 01 '21 at 10:12