Ask HN: Have You Ever Found an Explicit Use for JavaScript Closures?
"Frankly, you can’t get very far with JavaScript without learning about closures."
"If you can’t answer this question, you’re a junior developer. I don’t care how long you’ve been coding."
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
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 "mimic private field/property" and the module pattern. Past that though, any intentional use of closures seem limited to "if I loop through a set of dom elements and assign an event, the event will be assigned incorrectly", e.g.
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
console.log("My value: " + i);
});
}
// Each button will state "My value is 3" (Instead of 1,2,3)
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.
6 comments
[ 2.1 ms ] story [ 24.5 ms ] threadI 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.
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.
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:
If you don't do things this way, react-redux loses a lot of optimizations for connected components that have an ownProps argument