Javascript... reading that code got me thinking how it works as well..
I added console.log and see how the control flows:
function outer(a) {
console.log('outer: ' + a)
function inner(b) {
console.log('inner:' + b);
console.log('inner:' + a);
return a + b;
}
console.log(inner);
return inner;
}
var f = outer(3);
Output:
"outer: 3"
-----------------------------------------------------
function inner(b) {
window.runnerWindow.proxyConsole.log('inner:' + b);
window.runnerWindow.proxyConsole.log('inner:' + a);
return a + b;
}
-----------------------------------------------------
f(5);
"inner:5"
-----------------------------------------------------
"inner:3"
-----------------------------------------------------
8
-----------------------------------------------------
The first call
var f = outer(3);
sets variable "a" to 3, then outer function returns "inner" function definition.
Then 2nd call
f(5)
it calls the "inner" function, and assigning variable b = 5. In Javascript closure, variable "a" retain its value "3". So 5 + 3 = 8.