As my understanding, closure makes an environment to link functions and parameters outside the function and allow things inside the function to access them.
As below is a function with closure. When I execute this function three times.
add();
add();
add();
I expect I should get 1, because everytime I execute add(), It will redeclare counter as 0 and add 1. So it should be counter = 0, counter++, counter = 0, counter++, counter = 0, counter++. But why it turned out to be 3?
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
Second question is :
variable = (function() {})()
Why we add an extra parenthesis to enclose the function, and why another extra parenthesis after the function?
Thanks!