Javascript 2 – a function returning a function

I had some troubles with understanding this piece of code. [code lang=”js”]

var doSth = (function () {
var a = 1;
return function() {
alert(a++);
}
})();

/* The variable "doSth" points to an anonymous function
that is called afterwards via the brackets ().

It returns a piece of code that is then available in the variable doSth.
The returned code alerts the variable "a" incremented by 1.
FIX: it alerts variable "a" and then it is incremented by 1.

So now the variable "doSth" contains an executable code */

[/code]

The whole piece of code doesn’t alert anything until you call it. Duh, right? I thought it did of course πŸ™‚ Let’s call it then.

[code lang=”js”]
doSth();
/* first calling of the function alerts 1 */

doSth();
// when I call it the second time it alerts 2
/* Earlier i thought it would alert 1 again as the variable "a"
would get overwritten every time the doSth is called. It is wrong. */
[/code]

The outer anonymous function was already called so when you call doSth() it only calls the inner function that was returned, not the whole code. The beauty of this thing is that the inner function still has the access to the variable declared within the outer function. The variable “a”Β  is in a scope of the outer function.