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
Why is the function b being called twice?
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
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.
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.