How does a self-invoking function really works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

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.

25th Oct 2020, 11:56 AM
Logos
Logos - avatar
2 Answers
+ 5
Closures aren't magic! In fact, it's very simple. The outer function first calls itself, which gives the inner function "body" as the return value to `add` variable. Simple. Now, whenever the `add` is called it is actually running inner function, hence the scope of the `counter` variable is preserved and it get increases!! Eddy Ricchy further reading https://stackoverflow.com/questions/111102/how-do-javascript-closures-work
25th Oct 2020, 12:08 PM
777
777 - avatar
+ 2
@vrintle I got it!!! Thank you so much for your help. Small answer for you, big leap for me. Yippee!!!
26th Oct 2020, 6:15 PM
Logos
Logos - avatar