Phillip Phillop Phillip Phillop - 3 months ago 18
Javascript Question

iife javascript variable lifetime

how come a variables value within the immediate scope of an iife, survives in a similar way to a global variable in terms of holding it's value. This is really confusing me.

(function(){
var display = document.getElementById('display');
var button = document.getElementById('button');
var count = 0;
display.innerHTML = 0;

button.onclick = function(){
count ++;
display.innerHTML = count;
}
})();

Answer

It survives because there's still a reference to it in one of your HTMLElements.

When you attach that lambda to the button.onclick property, there is a reference to count inside the lambda.

So long as that HTMLElement survives, or that onclick property remains assigned to that lambda, then count will survive too.