Reputation: 76
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 ().
Upvotes: 0
Views: 38
Reputation: 816472
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.
Upvotes: 2