function makeAdder(x) {
return function(y) {
console.log("X:" + x + " Y:" + y);
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2));
console.log(add10(2));
Ok, I am a bit confused with this example on developer.mozilla under closures.
If someone can explain with as much detail as possible in order for me to get my head around closures.
Ignore the console.log, I just added that to see what values are displayed and from that I can see that x is 5 and y is 2 when you execute add5 for example.
I consoled add5() to see what I get and I got NaN - and I am guessing that is because I have not specified an argument because it wants one and can't add a number to undefined.
So the confusion is that argument y in madeAdder's inner function.
Hope someone can provide a much better explanation than mozilla...i think the clue is environments but I'm new to this so need help from experts.
Thanks
makeAdder
required one parameter calledx
and returns a new function requiring the parametery
. When executing this inner function, thex
of the outer scope will be added to the parametery
and the sum is returned.var add5 = makeAdder(5);
will create a new instance of the inner function and store it toadd5
.x
for this inner function is set to5
. when executingadd5
withadd5(2)
this will return7
, because thex
value ( outer scope5
) will be added to the parameter2
.The procedure for
add10
is equaly.Edit when not passing a parameter ( either inner or outer function or both ) the parameter (
y
orx
or both ) will beundefined
.undefined+number
orundefined+undefined
returnsNaN
because one or more of the summand is not a number.Edit 2: Procedure Walkthrough:
var add5 = makeAdder(5);
will setadd5
to:Because
makeAdder(5)
returns its inner function and sets x to 5. So when now executed withvar sum = add5(2);
this generated function will calculate and return5 + y
(5 + 2
).Note: it's not really setting x to
5
( instead its still a reference to the outer x ) but i think this is easier to understand and does not change anything in this particular example