Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda