Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

217
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda