How does a self-invoking function really works?
While learning about the self-invoking function there was an example to solve a counter dilemma such that suppose you want to use a variable for counting something, and you want this counter to be available to all functions, then it's best to use a self-invoking function. But I don't really understand the code and the concept too well. This is the code: var add = (function() { var counter = 0; return function() {counter += 1; return counter} })(); add(); //counter is 1 add(); //counter is 2 add(); //counter is now 3 What I mainly understand from the concept is that the self-invoking function can call itself and it only runs once. But if it only runs once, then how is the add() method here used three times, each incrementing the counter variable by 1? Secondly, while the self-invoking function is calling itself, it declares the counter variable and assigns 0 to it. It also returns an anonymous function that increments the counter variable by 1 and returns it's value. Doesn't this mean that the value of the counter variable should be 1 when the self-invoking function calls itself? Using the add() method 3 more times, shouldn't the value of the counter variable be 4? Thirdly, on calling the add() for the first time, is it not calling the self-invoking function again, and if so, isn't the counter variable reassigned to 0? I am beginner in JavaScript programming.