Here is a possible use of a closure:
var getUid = function () {
var uid = 1;
return function () {
return uid++;
};
};
// invoke the wrapping function immediately
// to create a single local scope
getUid = getUid();
getUid(); // 1
getUid(); // 2
getUid(); // 3
As you can see, the closure allows to keep the "uid" local variable "alive" between function calls. Its value is retained in memory, it is persistent, unlike when there is no inner function:
var getUid = function () {
var uid = 1;
return uid++;
};
getUid(); // 1
getUid(); // 1
getUid(); // 1
To summarize, the interesting stuff about closures is the ability to make local variables persistents.
In your example there is something that is worth being noticed though. Pay attention to the fact that writing a()()
is the same as writing (a())()
. This means that you call the wrapping function "a" first, which creates a new scope, thus, everything inside "a" is entirely recreated.
If you keep creating new scopes this way, there is no reason to use a closure. Indeed, doing this you loose the abilty to keep variables alive between function calls (as explained above). Let's see what would happen to getUid()
if used this way:
var getUid = function () {
var uid = 1;
return function () {
return uid++;
};
};
getUid()(); // 1
getUid()(); // 1
getUid()(); // 1
Same result as if there was no inner function. Not very useful right? However, you can still take advantage of calling the wrapping function repeatedly if you need to create multiple scopes, but you'll have to store inner functions into variables:
var getUidA = getUid(); // scope A
var getUidB = getUid(); // scope B
getUidA(); // A 1
getUidA(); // A 2
getUidB(); // B 1
getUidA(); // A 3
getUidB(); // B 2
I'm not sure there is much more to say regarding the fundamentals of closures, fellow programmers will judge. Anyway, if you feel ready for headaches, you might be interested in what's going on at low level in memory: https://stackoverflow.com/a/31778897/1636522.