Friends, teach javascript and encountered a problem.

Here is the code:

function makeCounter() { var currentCount = 1; return function() { // (**) return currentCount++; }; } var counter = makeCounter(); // (*) // каждый вызов увеличивает счётчик и возвращает результат alert( counter() ); // 1 alert( counter() ); // 2 alert( counter() ); // 3 // создать другой счётчик, он будет независим от первого var counter2 = makeCounter(); alert( counter2() ); // 1 

The counter works correctly - it was called 3 times - the value is 3 and has. But why is this happening? Indeed, in the function, it is assigned the value 1 each time. Therefore, each time the function is called, it must produce 1. At least in C like languages. I suppose that this happens because the variable was once declared and it became some kind of global, and in subsequent calls to this function, this line is simply skipped ... In general, I would appreciate an explanation.

Reported as a duplicate by participants Aleksey Shimansky , Duck Learns to Hide , Vadim Ovchinnikov , pavel , Pavel Mayorov Jan 16 '17 at 6:33 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

There is a good closure article:

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure “remembers” the environment in which it was created.

In your case, the function makeCounter returns a function that “captures” currentCount and therefore, causes the counter instance to be executed — you increment the counter. Creating counter2 you create a new instance that contains a new counter currentCount , so they run independently.

In addition, there is already an answer to your question: How do closures work in JavaScript