The simplest description of a closure I've heard is:
It's a way for a function to have indefinite access to the environment it was created in.
So in:
var a = function(b) { /* "outer" aka "functionofb" */
return function(c) { /* "inner" aka "functionofc" */
return y + b + c;
}
};
We're going see how this gives the inner function indefinite access to (a copy of) variable 'b' as it existed when inner sprang into life. (In this example the inner function never changes the value of its copy of 'b', but it could.)
So to walk through your example, lets start Here:
x = 2;
var fn = a(x);
The variable a "points" to an un-named (anonymous) function (the one with 'b' as an arg), so this is essentially:
fn = functionofb(x);
or :
fn = functionofb(2);
Now 'functionofb' is a function which returns a function. The function it returns is:
function(c) {
return y + b + c;
}
(which is also anonymous, so we will call it `functionofc')
So:
function(c) {
return y + 2 + c; /* here 'b's value is 'captured' by the closure */
}
Then we have:
y = 3;
And do:
fn(5);
Which is just:
functionofc(5);
which gives us:
return y + 2 + c;
Or:
return 3 + 2 + 5; /* 'y' was never captured, the current value is used */
Which is the desired answer:
10
Everything else are just red herrings.
For a more complete discussion of JavaScript closures in general see How do JavaScript closures work?