# 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.

←→
↑
en ru