-1

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;
    }
})();
Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

1

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.

Mulan
  • 129,518
  • 31
  • 228
  • 259
1

That's called a "closure".

Your function refers to display and count in its body, so it will "capture" those variables and "keep them alive" as long as it itself is alive (which it will here because you attached it to the DOM as an event handler).

Thilo
  • 257,207
  • 101
  • 511
  • 656