user2668069
user2668069

Reputation: 249

How can functions be called as an argument for a function?

The code that brought this question to my mind (and that I am trying to understand) is:

function sum(numbers) {
    var total = 0;
    forEach(numbers, function (number) {
        total += number;
    });
    return total;
}
show(sum([1, 10, 100]));

p.s forEach is a function that does this:

function forEach(array, action) {
    for (var i = 0; i < array.length; i++)
        action(array[i]);
}

I would like an explanation of how the code above works, as I don't understand how a function can be called as an argument for a function.

Upvotes: 0

Views: 116

Answers (1)

Bergi
Bergi

Reputation: 664434

I'm mostly concerned about how a function can be called as an argument for a function.

It's not called in the argument - the function itself is passed. In JavaScript, functions are first-class values; they are objects which can be invoked with parenthesis, but they also have normal properties (like .prototype or .name) and inherited methods (like .call, .bind). Have a look at the docs for Function objects.

Your sum code is creating an anonymous function, and passes the reference to it into the forEach function where it is stored in the action variable. It then is getting invoked from there.

The concept of passing functions around to be invoked with values determined by another method is named callbacks.

Upvotes: 3

Related Questions