can you explain how arguments are passed automatically in callback functions?
1. const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2. arr.sort(comFunc);
3. /* how arugments 'a' and 'b' are passed inside comFunc in sort() function */
4. function comFunc(a, b){
5. return b - a;
6. }
7. arr.forEach((item)=>{
8. console.log(item);
9. })
In the code above I'm confused how a and b are automatically passed as an argument inside sort()? can you explain the 2nd line in the code that how comFunc get his arguments?
The Array.prototype.sort function will iterate through the array, passing the values at the current index(a) and the next index(b) to the callback function you have provided.
As per your example above it should make the following calls per iteration
0: a = 1; b = 2
1: a = 2; b = 3
2: a = 3; b = 4
...
Your comFunc is a variable with Function type. It will get called later by sort method internally and they take care of passing the parameters with appropriate values.
Here is a simpler example since sort is a bit complicated. Let's look at Array.filter function instead:
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
We can implement such function like this:
function filter(arr, filterFunction) {
const result = [];
for (let item of arr) {
if (filterFunction(item)) {
result.push(item);
}
}
return result;
}
When creating the function, you do not know what "end-developer" want to filter with. Therefore, you let developer pass a function, and it's developer's job to make sure it's a function that accept an item and return a boolean-like result. Our job is to pass the item and act accordingly to the result. For example:
const arr = [1,10,5,3,2];
const filteredArr = filter(arr, require5OrMore);
function require5OrMore(item) {
return item >= 5;
}
// filterArr now contains only items that are >= 5 (10 and 5)
Note that in reality, the above code can be simplified using anonymous and/or arrow function:
const filteredArr = filter(arr, item => item >= 5);
Now if you still cannot understand why it is happening, you can put some breakpoint in the above filter function and require5OrMore function and check the values as the code runs through it.