Classic example:
function createAdder(x) { return function add(y) { return x + y; } } var addTwo = createAdder(2);
The idea is that you want to create a function, but the function you want to create depends on something. In this case, we wanted to create the addX function.
See Chapter 5 of Eloquent Javascript for more details. In particular, the section of higher orders .
It may also be drier. Consider:
function createSecretAdder() { var secretNumber = generateSecretNumber();
vs.
function createSecretAdder() { return function(n) { var secret = getSecretNumber();
The first is DRYer and faster than the last. This should concern your comment and update to your question.
Note: you need to understand closures to understand how this works.
For the reason for calling him immediately, see here .
source share