This question has already been answered:
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.