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

185
Views
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 answers
Answer question

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 Report

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