My biggest confusion is how can a function itself be called as an argument in itself …and how this is resolved by JS,
Let’s start understanding this
A function that calls itself is called a recursion
.
( generally a proper recursion example is a function that factorialize a number)
Here’s the dumbest example I can think of:
function recursion(n) {
while (n > 0) {
console.log(n)
return recursion(n-1)
}
return n;
}
recursion(4)
How does the above function is executed in JS?
Basically the function start calling with a value of 4, and then call itself with a value of 3, and so on, each time adding a new function to the pile of function (the stack) to execute. until we reach a return point.
(no return == maximum stack exceeded error )
So this is our call stack.
recursion(4)
--> console.log(4)
--> recursion(3)
--> console.log(3)
--> recursion(3)
[....]
--> n == 0 RETURN n.
In your example everything is way more complicated since each function is waiting for a new argument to be called before reaching a return point, thus you have different function in your stack waiting for another function to resolve first.
As per your example, is really convoluted, but remember that contrary to my example where you keep on calling itself until you reach a return, your function immediately return something.
So when dealing with this:
testBind(testBind, add);
You are not dealing with a function that call itself, since testBind
, once called is
return function (b) {
return fn(a,b)
}
a new function that is waiting for a new argument, that knows you want to:
return a + b;
but is still missing 2 arguments to do so.
As per the complete execution I’m afraid it’s quite hard to do it on paper
I suggest you heading to http://pythontutor.com/ and try it in a step-by-step execution.
Hope that I’ve cleared that up even just a little