When you call your makeAdder(5)
, it returns the reference to a new function.
function(y) {
return x + y;
};
So add5
keeps the reference. After it when you call add5(2)
, you pass the 2
to the function. In it when it wants to return x + y
, it starts to find the variables. Starting from x
, it looks and see's that the x
is not defined in it and goes to the scope
in which inner function was defined ` here
function makeAdder(x) {
return function(y) {
return x + y;
};
}
It see's than x
was defined here, because you call and pass x
during var add5 = makeAdder(5);
. After it goes to find y
and finds in it's scope. And after all returns x + y
.
The idea is this, every function has a reference to it's creater (where it was defined) and when it doesn't find a variable, it goes to find in it's greater and so till to global scope.