Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I like the diagnosis.

My JS is terrible, but it seems like once you make the counter a global variable it is just better to change it to have an atomic dedicated count function. So instead of incrementing the counter in simple, a globalCount() function gets called that isolates the state. Something like

  {
    let i = 0;
    var counter = function (){
        console.log(++i);
    }
  }
Then call counter() to count & log and document that something horrible and stateful is happening. I wouldn't call that a global variable although the article author disagrees.


How is a globally-scoped closure not a global variable?


Because there is no intent, need or reason to vary it.

Nearly everything in RAM is technically a global variable to someone who is keen enough. Programming depends on a sort-of honour system not to treat things like variables if it is hinted that they shouldn't and it doesn't make sense to. Otherwise we can all start making calls to scanmem & friends.


Right but closing over a state with a function and giving that closure a name seems to quack like a duck to me. Maybe it's just because I'm a scheme guy and we're more upfront about this.


The situation is ugly because there is global state by design. But I don't see why the fact that the closure is stored in a mutable location would be a concern for you. Can you think of any conditions where someone would modify it? I'm not really seeing it, and I don't know what your alternative suggestion is going to be to stop them technically.

I can tell you when someone would modify a counter variable - every time it needs to be incremented. It leaves open a lot of room for bugs in unexpected parts of the code. Gating access behind a stateful function makes doing the wrong thing more expensive.


I think we're talking past each other here. The issue is that the enclosed state of counter is exposed globally and can be accessed without synchronization. I suppose yes one could also reassign counter to a different function (and you'd need to be aware of that) but my point is that you still need some kind of sync if you're calling counter all over the place, just like you would with a global variable


> The issue is that the enclosed state of counter is exposed globally and can be accessed without synchronization.

Maybe throw up a code example? I don't follow what you're getting at.


A function isn't a variable.


A function can absolutely be a variable. This isn't even an anonymous closure.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: