Closures and IIFE in JavaScript

As you already know, you can call an anonymous function in-place and assign the result of the work to some variable:

let result = function() { return '!'; }(); console.log(result); // shows '!'

Often the immediately invoked function is then enclosed in parentheses, although this is not necessary. This is done so that it is immediately clear that the function is called in-place:

let result = (function() { return '!'; })(); console.log(result); // shows '!'

Let now the result of the function called in-place be an anonymous function:

let func = (function() { return function() { console.log('!'); } })(); func(); // shows '!'

Let's make the returned function store the variable num in the closure:

let func = (function() { let num = 1; return function() { console.log(num); } })();

If you add num++, then the function func will become a ready-made counter:

let func = (function() { let num = 1; return function() { console.log(num); num++; } })(); func(); //shows 1 func(); //shows 2 func(); //shows 3 func(); //shows 4 func(); //shows 5

Without looking into my code, implement the same counter on your own.

Modify the operation of the counter so that it counts up to 5, and then starts counting again.

Comparison with the previous method

Let's compare our counter with the counter using closure we did earlier:

function test() { let num = 1; return function() { console.log(num); num++; } } let func = test(); func(); //shows 1 func(); //shows 2 func(); //shows 3 func(); //shows 4 func(); //shows 5

As you can see, our new method is simpler: the ready-made counter immediately gets into the variable, unlike the old method, in which we have an additional function test. In addition, in the old way, you can create several counters:

function test() { let num = 1; return function() { console.log(num); num++; }; }; let func1 = test(); // the first counter func1(); //shows 1 func1(); //shows 2 let func2 = test(); // the second counter func2(); //shows 1 func2(); //shows 2

In the new method, only one unique counter will be obtained. If you really only need one counter, then it's convenient to use the new method: this way you will protect yourself from accidentally creating multiple counters.

enru