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

186
Vistas
about javascript callback example

a = [3, 1, 2];

function b(v1, v2) {
  console.log('c', v1, v2);
  return 0
};

a.sort(b);

console.log(a);

a result of this script is like this

c 31 c 12 [3, 1, 2]

my question is

  1. Why is the function b being called twice?

  2. And in the first log console.log('c', v1, v2);

why the v1 value is the first array value of a. it's "3"

also why v2 is the second array value of "a"

in the second log console.log('c', v1, v2); Why are the 2nd and 3rd values of the array in v1, v2 the result is "c 1 2"

I can't understand

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The compare function is called repeatedly (being passed two elements from the array each time) until the array is completely sorted.

You have three items in the array so it has to be called at last twice.

The specific values that get passed each time will depend on the sort algorithm the JS engine has selected (this is an implementation detail, not something mandated by the JS specification). The order that elements are compared in a bubble sort will be different to a quick sort.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Why is the function b being called twice?

sort calls the callback as many times as it needs to in order to sort the array. Each time, it calls the callback with two elements from the array so the callback can tell it what order those two elements should be in.

And in the first log console.log('c', v1, v2);

why the v1 value is the first array value of a. it's "3"

also why v2 is the second array value of "a"

They won't be, necessarily; sort can call the callback with whatever elements it wants. The specific algorithm used for sorting isn't dictated by the specification. All that's dictated is that it be stable (not unnecessarily change the order of equivalent elements) and that it do its work using the provided callback, if any.

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