-1

When I was trying to understand how the sort(i mean native js) function works (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) and used their function:

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);

I added a console.log, but the first element was the second:

 let numbers = [4, 2, 5, 1, 3];
    numbers.sort((a, b) => console.log('a - is - '+ a));
    console.log(numbers);

Why? Thanks in advance!

Nina
  • 31
  • 3
  • 6
    Now that arrow function in the second example is returning `undefined`. Do `numbers.sort((a, b) => {console.log('a - is - '+ a); return a - b;});` – zero298 Sep 21 '21 at 18:46
  • 1
    See [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/q/28889450/691711). – zero298 Sep 21 '21 at 18:49
  • 1
    You added the `console.log` but removed the comparison and don't actually return anything. – phuzi Sep 21 '21 at 18:49
  • 1
    https://stackoverflow.com/questions/234683/javascript-array-sort-implementation – Amit Kumar Singh Sep 21 '21 at 18:56

1 Answers1

-1

You neglected to return anything (other than undefined) from your logging version which is why it is failing to sort. You also only log one of the values.

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => {
  console.log('a: ' + a + ' - b: ' + b);
  return a - b
});
console.log(numbers);

Taking a look at the spec doesn't explicitly state why the items are passed in a seemingly reversed order and seems to be open for interpretation by JS engine implementors. As such I might expect to see different behaviour with other JS engines although it's just as likely that they all implement this the same way.

phuzi
  • 12,078
  • 3
  • 26
  • 50
  • but the first element (a) is not 2 but 4 – Nina Sep 21 '21 at 18:56
  • @Nina The `sort` method decides what params its callback gets; there's no "first" or "second", there's `a` and `b`, and the user doesn't decide what references they get. – Dave Newton Sep 21 '21 at 18:58