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!
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.