I'm grappling with the concept of a function that I grasp.
function forEach(array, action) {
for (var i = 0; i< array.length; i++)
action(array[i]);
}
When we use this function, like
forEach([1,2,3,4,5], console.log);
, it essentially swaps out 'action' with 'console.log' in the body. And everything runs smoothly. Right?
However, things get a little tricky when an anonymous function is thrown into the mix.
var numbers = [1, 2, 3, 4, 5], sum = 0;
forEach(numbers, function(number) { sum += number; });
In this scenario, an anonymous function serves as an argument. How exactly does this function cycle through each element of the 'numbers' array, placing it into its parameter 'number'? It's puzzling.
To simplify matters, I could do something like:
var FindSum = function (number) {
sum += number;
};
forEach(numbers, FindSum);
But I still find myself perplexed by how the 'FindSum' function receives a number.