Can someone please explain in plain language how this code works to give a result of 9?
what happens to the return of the inner function? Im assuming that the enclosing function return is assigned to the variables addTwo and addFive... where does the inner function get its argument (number)? I
m totally lost on this and the tutorial doesn`t explain it.
function makeAddFunction(amount) {
function add(number) {
return number + amount;
}
return add;
}
var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1));
var addTwo = makeAddFunction(2);
1. 2
is assigned as amount
and bound within the function scope. The inner add
function has access to this, and so keeps it "cached".
So what is returned is essentially function(number) { number + 2 };
var addFive = makeAddFunction(5);
2. 5
is assigned the same way, and function(number) { number + 5 };
is returned.
show(addTwo(1) + addFive(1));
3. function( number ) {number+2}
is invoked and 1
is fed to the function, so 2+1
is returned which is 3
.
4. function( number ){number+5}
is invoked and 5
is fed to the function, so 5+1
is returned which is 6
.
5. 6
and 3
are added, so we get 9
.
6. 9
is fed to the show
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With