I'm currently finishing reading up on JavaScript. I am on the chapter about closures in JavaScript (to allow "private variables"), on http://www.w3schools.com/js/js_function_closures.asp.
The example is a counter:
<!DOCTYPE html>
<html>
<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>
</html>
It states that it makes use of a self-invoking function to set the counter to 0 once, and increments counter by one for every iteration of add(). However, I see in the code that the curly braces used to self-invoke a function is around both the counter = 0 and the function to increment counter. It's just difficult for me to visualize how exactly both commands can be inside the self-invoking function but one runs only once, while the other runs every iteration.
countervariable and returns a function that does work on thecountervariable. So when you calladd()you are not running thevar counter = 0code, you're running thereturnof the IIFE (which happens to be a function).counter += 1can be++counter.