While exploring some tutorial code, I came across an interesting concept involving invoking a function within the sort
method in JavaScript. For example, let's say I have an array containing integers:
var numbers = [8, 6, 2, 4];
To sort these integers from greatest to least, I created the following sorting function:
function numSort(num1, num2) {
if (num1 > num2) {
return 1;
} else if (num1 === num2) {
return 0;
} else {
return -1;
}
}
And then applied the sort method to my array like this:
numbers.sort(numSort);
There are a couple of aspects that confuse me. Firstly, this function only takes two arguments (num1
and num2
) while my array contains more elements than that. My questions are:
- How does this function iterate through each element even though it only has two parameters,
numm1
andnum2
? - How and why is no argument passed when calling this function within the
sort
method?