Reputation: 728
I have this code.
<body>
<p>Counting with a local variable.</p>
<button type="button" onclick="myFunction()">Count!</button>
<p id="demo">0</p>
<script>
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
</body>
The variable add is assigned the return value of a self invoking function.
Does this mean, every time add is called,only return of function is invoked not the whole function ?
If not,Can anyone please explain it?
Upvotes: 0
Views: 46
Reputation: 318182
Yes, only the returned function inside the IIFE is called when the add()
function is called.
The IIFE is called on pageload when the parser encounters it during the execution phase, and returns the other function as a reference to be called later.
The only thing the outer IIFE is doing is keeping the counter
variable inside it's own scope.
IIFE == Immediately-invoked function expression
Upvotes: 3
Reputation: 67296
In the following code, you have a function that returns a function:
var add = (function () {
var counter = 0;
return function () {
return counter += 1;
}
})();
The outer function is immediately executed. So, add
is assigned to the inner function:
function () {
return counter += 1;
}
As you can see, the counter
variable in the inner function refers to the context of the outer function (where counter
is declared). This context is called closure
and is still referenced in the inner function. So, JavaScript keeps this context alive.
As @RobG points out, the internal JavaScript execution rules are more like: the identifier counter
in the inner function is first resolved in the inner execution context. Since it isn't found there, the next object on the scope chain is searched, which is the outer execution context and counter
is found there.
So, by the magic of closure, the counter
variable can still be accessed and changed when calling the inner function (using add
).
So, when calling add
, you are executing the inner function, which is closing over counter
.
Upvotes: 1