
Ask HN: Have You Ever Found an Explicit Use for JavaScript Closures? - madeuptempacct
&quot;Frankly, you can’t get very far with JavaScript without learning about closures.&quot;<p>&quot;If you can’t answer this question, you’re a junior developer. I don’t care how long you’ve been coding.&quot;<p>https:&#x2F;&#x2F;medium.com&#x2F;javascript-scene&#x2F;master-the-javascript-interview-what-is-a-closure-b2f0d2152b36<p>Ever since reading this dramatic (and, in retrospect, idiotic) statement, I have been kind of obsessed with figuring out the actual use for closures. I will grant the &quot;mimic private field&#x2F;property&quot; and the module pattern. Past that though, any intentional use of closures seem limited to &quot;if I loop through a set of dom elements and assign an event, the event will be assigned incorrectly&quot;, e.g.<p><pre><code>  var buttons = document.getElementsByTagName(&quot;button&quot;);  
  for (var i = 0; i &lt; buttons.length; i++) {  
    buttons[i].addEventListener(&quot;click&quot;, function() {  
      console.log(&quot;My value: &quot; + i);  
    });
  }

  &#x2F;&#x2F; Each button will state &quot;My value is 3&quot; (Instead of 1,2,3)
</code></pre>
So, after reading chapters in three books and a ton of articles and stackoverflow posts, I ask you HN - have you ever used a closure intentionally? If so, please share.
======
eschutte2
Constantly - it's so important that it's just kind of in the background of
everything I do. Doesn't it make currying and point-free style much easier?

~~~
madeuptempacct
but why? From first google search result ([https://hackernoon.com/currying-in-
js-d9ddc64f162e](https://hackernoon.com/currying-in-js-d9ddc64f162e)):

    
    
      function sum3(x) {
        return (y) => {
          return (z) => {
            return x + y + z;
          };
        };
      }
      console.log(sum3(1)(2)(3)) // 6
    

How is this cleaner than?

    
    
      sum(1,2,3);
    

I have seen examples like this before, but I don't understand the point of
this either. I guess I will read up on currying more, thank you.

~~~
eschutte2
Sorry, just got back and saw your reply. This is too big a topic to go into
here and there's already plenty written on it. Sum is not a realistic use
case. If you're doing Javascript, maybe look at lodash/fp for ways people
really use currying.

I think my answer to "why" would be: if your mind is already geared to think
about problems in terms of composition of functions, then currying (for
example) is just one necessary and natural thing that falls out of that.

~~~
madeuptempacct
I appreciate you getting back to me!

------
arenaninja
I write a LOT of React code, and I abuse closures daily

The statement you quote is overly dramatic, and it takes maybe 5 minutes to
clearly explain the concept to someone that grasps the basic language syntax.
The usefulness is more difficult to lay out clearly

Where it comes up very often for me is when using mapStateToPropsFactory from
react-redux, like this:

    
    
        // a closure for ownProps is created
    
        // the factory is not invoked everytime the component changes props
    
        const mapStateToPropsFactory = (_, ownProps) => {
    
          const { uniqueId } = ownProps;
    
          return function mapStateToProps(state) {
            return {
              usefulThing: state.usefulThings[uniqueId],
              ping: state.pong,
            }
          }
       }
    

If you don't do things this way, react-redux loses a lot of optimizations for
connected components that have an ownProps argument

------
rl3
While there's many legitimate and peculiar use cases where closures make sense
when writing properly engineered code, my favorite use is simply abusing them
in one-off or ad-hoc code where performance or correctness isn't a concern.

Basically just using them as lazy shortcuts to avoid the hassle of argument
passing. It's particularly great when you have a function scope that's three
or four levels deep, and you're referencing a variable via closure that's in
the top-level function scope. Much less work.

