0

I tried to make my own implementation of a click counter. It works, but I dont understand how the store variable, which literally stores the closure for abc(), at a time when count=0, is able to edit the value of count in the closure, every time that it is called. Isn't it supposed to be an immutable snapshot?

function xyz(){
    let count=0;
    function abc(){
        return ++count;    
    }
    
    return abc;
}

var store = xyz();

document.addEventListener('click',()=>{
    console.log(store());
});
sayandcode
  • 1,775
  • 1
  • 11
  • 24
  • As proven by your own example, closures don't take snapshots, they update the outside variables via reference. `count` never re initializes because you don't call xyz again – Asplund Apr 19 '22 at 12:41
  • @Undo `count` would not be re-initialized even if you called `xyz` again, that would create a new closure. – Teemu Apr 19 '22 at 12:45

0 Answers0