I have the following problem below:
My For Each
Write a function myForEach that accepts an array and a callback function. The behavior of myForEach should mirror the functionality of the native .forEach() array method as closely as possible.
Below is the code:
let sum = 0;
function addToSum(num) {
sum += num;
}
let nums = [10, 20, 30];
function myForEach(anArray, callback){
for (let i=0; i<anArray.length; i++){
let num = anArray[i];
//console.log(num)
// I don't understand what this line of code is doing...
callback(num, i, anArray);
}
return undefined
}
myForEach(nums, addToSum);
console.log(sum); // 6
The above code works in this higher order function problem but I don't understand why. Specifically, what is the following line of code mean:
callback(num, i, anArray);
why are there 3 arguments? and where are these arguments getting passed to?