Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
Why the first item in native javascript function sort() - is the second in my array?

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!