0

I am new to programming and trying to understand callback functions and functions in general. This program compares 2 values passed in the functions(using callback) and return true/false to us.

function func1(param1, callback) {
    return callback(param1);
}

function func2(param2) {
    return function(param3) {
        return param3 > param2;
     }
}

var functionResult = func1(10, func2(9)); 
console.log(functionResult);       // prints - true

Question - In this program above, how does the return function inside the func2 function, return the value directly to us, without being invoked? I thought in this line var functionResult = func1(10, func2(9)); func2(9) will return only the text

function(param3) {
        return param3 > param2;
     }

and then I would have to invoke it again with ().

1

1 Answer 1

2

how does the return function inside the func2 function, return the value directly to us, without being invoked?

It is invoked. func1 invokes it here:

callback(param1)

func2(9) will return only the text ...

That's not text, that's actually a function (object). It is passed to func1 which in turn calls it and returns its return value.

and then I would have to invoke it again with ().

Yes, which, again, is what func1 does:

callback(param1)

Lets take things apart:

 var functionResult = func1(10, func2(9)); 

is the same as

var func2Result = func2(9);
var functionResult = func1(10, func2Result);

Since we know what func1 does, we can replace the call to it with it's implementation. 10 is passed as param1 and func2Result is passed as callback, so the code becomes:

var func2Result = func2(9);
var functionResult = func2Result(10); // callback(param1);

Now you should be able to see that the return value of func2 is actually called.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, the taking things apart part really made it clear to me
I just realized, the code is essentially func2(9)()
Yes, you can also omit func2Result... maybe I should have done that instead, but I thought maybe seeing ()() is also confusing ¯\_(ツ)_/¯

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.