Forrest
Forrest

Reputation: 107

Placing a function as a parameter within another function

I have the following code:

var doSomething = function(paramOne, paramTwo, fn){
    paramOne = paramOne + 3;
    paramOne = paramOne + 1;
    paramOne = paramOne * 8;

    return fn(paramOne, paramTwo);
};

function sum(paramOne, paramTwo){
    return paramOne + paramTwo;
};

var foo = doSomething(2, 2, sum);

alert(foo);

This code coming from a source I'm learning from...so it works fine.

I understand what's going on..kind of but I was hoping someone here could explain it?

The part I'm not understanding so well is why paramOne and paramTwo are in brackets on these two lines:

return fn(paramOne, paramTwo);

and

function sum(paramOne, paramTwo){

If someone could explain this to me it would be much appreciated.

Thanks.

Upvotes: 0

Views: 48

Answers (2)

JLRishe
JLRishe

Reputation: 101662

You seem to be getting confused because paramOne and paramTwo are used in different contexts.

Perhaps this would be clearer:

var doSomething = function(paramOne, paramTwo, fn){
    paramOne = paramOne + 3;
    paramOne = paramOne + 1;
    paramOne = paramOne * 8;

    return fn(paramOne, paramTwo);  // since `sum` is the function being passed in
                                    // below, the result here is the same as calling
                                    // sum(paramOne, paramTwo)
};

function sum(firstNumber, secondNumber){
    return firstNumber + secondNumber;
};

var foo = doSomething(2, 2, sum);

alert(foo);

As you can see here, the sum function's parameters are completely unrelated to the ones in doSomething. You have to pass values into sum() in order to give it values to add together and return.

Does that make more sense now?

Upvotes: 1

Slava Fomin II
Slava Fomin II

Reputation: 28611

This line here: return fn(paramOne, paramTwo); consists of two parts: return expression and expression itself, which is a call to a function fn with two arguments paramOne and paramTwo.

This line: function sum(paramOne, paramTwo){ is a definition of the function sum.


To better explain it we should start with this line: var foo = doSomething(2, 2, sum);. In this line we are calling a function doSomething and passing three arguments to it. First two arguments are two integer values: 2 and 2, and the final argument is a function sum. In JavaScript you can pass functions as arguments to another functions by specifying it's name in the call.

When function doSomething is actually called all passed arguments are bound to local variables, specified in the definition of the function: function(paramOne, paramTwo, fn). So 2 will become paramOne, the other 2 will become paramTwo and sum will become fn.

And when we call fn() later on we are actually calling sum().

And the sum function here is pretty self explanatory.

If you have additional question just ask them in the comments to this answer. I will be glad to update my answer.

Upvotes: 0

Related Questions