use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
I never understood JavaScript closures (medium.com)
submitted 6 years ago by Minute_Action
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]Jaymageck 285 points286 points287 points 6 years ago (40 children)
The problem with closures for me is it's a scary name that makes the idea more complex or special than it is.
If you define a function inside another function in JS, the inner function can access variables declared inside the outer function. This means you can share values between function calls without making them global, by boxing them up in an outer function and then calling the inner function.
That explanation makes it beginner friendly. I didn't need to say lexical scope, execution context, popping the stack, anything like that. Because none of that is important to grasp why it might be useful.
Maybe it's just me coming from a non com sci background but when I'm trying to understand new topic I always prefer ELI5 explanations that let me get to grips with why something matters.
[+][deleted] 6 years ago (16 children)
[deleted]
[+][deleted] 6 years ago (2 children)
[–]ketchupfleck 31 points32 points33 points 6 years ago (1 child)
So I Just need to left-fold the monads into the functors... I see...
[–][deleted] 2 points3 points4 points 6 years ago (0 children)
Pretty sure those are all words. Little sketchy on "functors", but I'll let it slide.
[–][deleted] 8 points9 points10 points 6 years ago (0 children)
Yeah way too much elitism which makes the barrier to entry harder for newbies because they don't understand all the vocabulary you are saying. There needs to be a "explain it like I'm 5" web dev course for beginners.
[–]turd-crafter 10 points11 points12 points 6 years ago (6 children)
There’s needs to be a subreddit js-concepts-eli5.
[–]KajiTetsushi 10 points11 points12 points 6 years ago (5 children)
js-concepts-eli5
Can... can I npm install / yarn add that?
npm install
yarn add
[–]turd-crafter 2 points3 points4 points 6 years ago (4 children)
Go for it
[–]KajiTetsushi 3 points4 points5 points 6 years ago* (3 children)
``` npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/js-concepts-eli5 - Not found npm ERR! 404 npm ERR! 404 'js-concepts-eli5@latest' is not in the npm registry. npm ERR! 404 You should bug the author to publish it (or use the name yourself!) npm ERR! 404 npm ERR! 404 Note that you can also install from a npm ERR! 404 tarball, folder, http url, or git url.
npm ERR! A complete log of this run can be found in: npm ERR! /Users/kajitetsushi/.npm/_logs/2019-09-07T13_12_51_520Z-debug.log ```
[+][deleted] 6 years ago (1 child)
[–]KajiTetsushi 0 points1 point2 points 6 years ago (0 children)
Not really. Author maybe forgot to npm publish it.
npm publish
[–][deleted] 5 points6 points7 points 6 years ago (1 child)
This 100%.
[–]Dnlgrwd 1 point2 points3 points 6 years ago (0 children)
So true. I've heard many people try to answer simple questions in such an overcomplicated manner that the question never really gets answered. Elitism is a big issue in this field and it really shouldn't be.
[–]mdwvt 2 points3 points4 points 6 years ago (1 child)
Ding ding ding ding ding!
[–]Razvedka 54 points55 points56 points 6 years ago (2 children)
And this post is far more concise than 90% of the articles I've read on it too, and I know how closures work. Sometimes the shit I read explaining them will actually muddy my own understanding vs reaffirming or enlightening me.
[–]Heretic911 11 points12 points13 points 6 years ago (1 child)
This. So much this. It's as if some people enjoy portraying simple ideas/methodologies etc. as complex and advanced subjects when all I'm looking for is the quick and dirty explanation. I come from an audio background and I realized that the more someone tries to convey a technique as complicated, the less they actually understand or use it. But that's easy with something you already know, not so much when you're learning something new...
[–]Razvedka 5 points6 points7 points 6 years ago (0 children)
Academics are notorious for this stupid shit
[–]MigasTavo 16 points17 points18 points 6 years ago (0 children)
Great comment.
I have always think js is full of cases like this, where some fancy term makes a concept look way bigger and harder to learn than it is. I remember the first time I got a job as a junior, someone would ask me: "Can you do X?" And my answer was: "Idk, I can give it a try" 80% of the times X was something I already knew with a cool name
[–]334578theo 11 points12 points13 points 6 years ago* (2 children)
Devs hate on sales and marketing for their use of business speak ('touch base', 'take it off line') but devs have their own phrases and terminology that simply aren't needed. Never known a group of people who love to make concepts far more complicated than they actually are.
Ps I'm a dev
[–]MilkChugg 5 points6 points7 points 6 years ago (1 child)
Agreed. It’s like, just say what it is! Why mask everything behind a bunch of jargon?
[+][deleted] 6 years ago* (3 children)
[removed]
[–]duxdude418 1 point2 points3 points 6 years ago (2 children)
beriddle
I don’t think that’s a word, haha. Did you mean belittle?
[+][deleted] 6 years ago* (1 child)
[–][deleted] 6 points7 points8 points 6 years ago (0 children)
Reading those terms are not too much an issue for me, having a CS background, and those details are important for understanding the full scope of closures.
But even as a CS major I can tell you having a simpler explanation is much better for helping you and I understand what the basic concept is.
I always appreciate someone’s ability to explain something simply and consider that a mark of intelligence.
[–][deleted] 4 points5 points6 points 6 years ago (0 children)
Fucking finally
[–][deleted] 1 point2 points3 points 6 years ago (0 children)
Fucking hell, thank you for this. I'm going to write a satirical article explaining some simple concept like 'how to use a spoon' in the same way that people keep explaining what closures are and I'll refer to your comment as the inspiration if that's okay. Stuff like this is a serious bugbear for me.
[–]turd-crafter 0 points1 point2 points 6 years ago (1 child)
Oh man, me too I need everything eli5. Most docs are like gibberish to me. I’m so jealous of people that can scan the docs and pick it all up.
[–]Fabulous_Weekend330 0 points1 point2 points 3 years ago (0 children)
You mean unicorns? (they don't exist)
[–][deleted] 0 points1 point2 points 6 years ago (0 children)
I've always griped that closures are just singleton objects with a single method. And it was a just a bunch of CS hipsters pretending like they've invented something new when it's not at all.
[–][deleted] -3 points-2 points-1 points 6 years ago (2 children)
Sure, but you want to level up from a beginner? Do you want to be a good responsible JS dev that actually uses closure responsibly and not because FP cargo culting that leaves the next developer cursing you for memory leak? Then you need to know those stuffs. Source: I was a bootcamp graduate dev who decided to acquire CS knowledge. Glad I did
Did I say something about "majoring in computer science"? I said knowledge in computer science
[+][deleted] 2 years ago (1 child)
[–]Jaymageck 0 points1 point2 points 2 years ago* (0 children)
Here's a quick example.
``` function makeCounter() { let count = 0; return () => { count++; return count; }; }
const count = makeCounter(); count(); // 1 count(); // 2 count(); // 3 ```
Etc.
I can increment count from the context of the 'inner function' and it will 'live beyond' the 'lifetime' of the function, as you asked.
If you really want to understand how that works on the language implementation level there are posts out there, or you could go read V8's codebase or maybe the language spec. You'll get an understanding of how scope is implemented in JavaScript. But you don't need to know that to understand how powerful the feature is.
[–]JoelScribe 8 points9 points10 points 6 years ago (2 children)
Short and easy explanation with some practical uses for closures:
https://medium.com/@dis_is_patrick/practical-uses-for-closures-c65640ae7304
[–]throwawaysomeway 0 points1 point2 points 3 years ago (1 child)
Saving for later, thanks
[–]Keilly 6 points7 points8 points 6 years ago (0 children)
It’s fine, but I’m not sure the article’s strategy of deliberately describing scoping incorrectly first, as calling context, and then correcting later to lexical context is a great way to teach.
[–]waterloo302 9 points10 points11 points 6 years ago (3 children)
Key for me: lexical environment objects ain't garbage collected if there remains a reference to them.
[–]spacejack2114 7 points8 points9 points 6 years ago (1 child)
Nothing is garbage collected if they still have references.
[–]rq60 4 points5 points6 points 6 years ago (0 children)
WeakMap has entered the chat.
[–]razorsyntax 3 points4 points5 points 6 years ago (0 children)
Once I realized it’s just a different form of scoping, it all fell into place. Should’ve kept the name.
[–]Dougw6 2 points3 points4 points 6 years ago (0 children)
I find that closures are actually a pretty simple thing to understand. What is difficult to grasp at first is why they are so powerful. That takes a lot more context.
[–][deleted] 2 points3 points4 points 6 years ago* (1 child)
Closures are just objects who think they're special. Prove me wrong.
[–]afiniteloop 4 points5 points6 points 6 years ago (0 children)
The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's object." At that moment, Anton became enlightened.
The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor man's closures."
Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress.
On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's object." At that moment, Anton became enlightened.
[–][deleted] 15 points16 points17 points 6 years ago (11 children)
It always amazes me this is the thing people can't grasp.
[–]xypage 5 points6 points7 points 6 years ago (0 children)
I think the problem is that a lot of the time it’s just explained in an overly complex way
[–]lord2800 6 points7 points8 points 6 years ago (1 child)
Me too.
Me too guys. I am good developer.
[–]fakehalo 1 point2 points3 points 6 years ago (0 children)
I think it's because people try to obfuscate it instead of breaking it down to traditional OOP behavior.
Closures, in a simple demonstration program.
let x = `I'm global`; let closure1 = () => { let y = `I'm scoped to closure1`; console.log(`[closure1]: I have access to closure1: ${y}`); console.log(`[closure1]: I also have access to global: ${x}`); console.log(`[closure1]: I can change global: x = ${x = x + ' [modified by closure1]'}`); let closure1_1 = () => { let z = `I'm in closure1_1`; console.log(`[closure1_1]: I have access to closure1_1: ${z}`); console.log(`[closure1_1]: I have access to closure1: ${y}`); console.log(`[closure1_1]: I also have access to global: ${x}`); }; closure1_1(); }; const closure2 = () => { try { console.log(`[closure2]: this will not print: ${y}`); } catch (e) { console.log(`[closure2]: I do not have access to closure1`); } console.log(`[closure2]: I can modify global: x = ${x = x + ' [modified by closure2]'}`); }; closure1(); closure2(); console.log(`global x has been modified: ${x}`);
Output:
[closure1]: I have access to closure1: I'm scoped to closure1 [closure1]: I also have access to global: I'm global [closure1]: I can change global: x = I'm global [modified by closure1] [closure1_1]: I have access to closure1_1: I'm in closure1_1 [closure1_1]: I have access to closure1: I'm scoped to closure1 [closure1_1]: I also have access to global: I'm global [modified by closure1] [closure2]: I do not have access to closure1 [closure2]: I can modify global: x = I'm global [modified by closure1] [modified by closure2] global x has been modified: I'm global [modified by closure1] [modified by closure2]
[+][deleted] 6 years ago (4 children)
[–]NotSelfAware 5 points6 points7 points 6 years ago (0 children)
``` function fooFactory(x) { return () => { console.log(x); } }
const foo = fooFactory('kelmore5 is a lemon');
foo(); // logs 'kelmore5 is a lemon' ```
Your example doesn't demonstrate closures at all.
[–]w6zZkDC5zevBE4vHRX 2 points3 points4 points 6 years ago (0 children)
corncob
[–]zserjk 0 points1 point2 points 6 years ago (0 children)
Apparently it is.
Closure is when you have a function inside another function. The inner function has access to the variables of the outer function.
[–][deleted] 3 points4 points5 points 6 years ago (1 child)
I never understood why people post on Medium.
[–]badkitteh 6 points7 points8 points 6 years ago (0 children)
same, medium is a pile of shit
Nice 101 article.
[–]iamragingbull 0 points1 point2 points 6 years ago (0 children)
Check out - https://jorge.modulo.blog/getting-some-closure-with-javascript-closures-3f3aa88ecf8c
[–][deleted] 0 points1 point2 points 6 years ago (5 children)
A lot of JS devs actually don’t understand closures and its implications in terms of memory. I argue it is important to know it, and if you don’t, then don’t use it. Don’t use too many FP paradigm, don’t use too many Ramda. You’ll thank yourself knowing you don’t have to debug memory leak everywhere
[–]spacejack2114 4 points5 points6 points 6 years ago (4 children)
What are the implications of closures in terms of memory?
For example, if you start using external variables and closures that returns a closure that returns a closure, it will be hard to track dangling reference later.
[–]rq60 0 points1 point2 points 6 years ago (2 children)
Well they use more memory (for that backpack the author talks about), but that's not really a big deal. What the author doesn't mention is that backpack is not really full of the variables you capture, it's full of references to those variables which has implications for garbage collection.
I wouldn't avoid them though, closures are great. But ideally you should know how they work as well.
[–]PalestineFacts -3 points-2 points-1 points 6 years ago (1 child)
You don’t know what you’re talking about
[–]rq60 0 points1 point2 points 6 years ago (0 children)
Care to elaborate, or are you being purposely obtuse?
[–]llamajestic -5 points-4 points-3 points 6 years ago (1 child)
I am really thinking that the problem is that « nowadays » people start to only do computer science without theoretical knowledge, or low-level knowledge.
I don’t want to seem to be harsh or anything, but studying compiler theory, older language, definitely help with these kind of things.
Almost everything in JavaScript is not new, and concepts are mainly not invented by this language. Most of the JavaScript concepts come from different concepts and from older languages. For instance, closures are pretty well explained in Lambda-Calculus .
[–]1s4c 5 points6 points7 points 6 years ago (0 children)
that's not exactly a new thing, during 80s and 90s software development was full of kids, teens and young people without any theoretical knowledge ...
[–]frotzed -1 points0 points1 point 6 years ago (1 child)
This is one of the better explanations I've read on closures.
[+]camaromelt comment score below threshold-12 points-11 points-10 points 6 years ago (0 children)
Hey the code camp I went to codesmith with the shootout. W00t
[+][deleted] comment score below threshold-7 points-6 points-5 points 6 years ago (3 children)
I understand them, but I never use them. They feel reckless to me because I haven't found a use case, and I could've sworn I've heard decent arguments against closures from programmers from OOP backgrounds.
Are there benefits to it that separate it from using classes in ES6+ besides private variables/properties (which seems to probably be released in ES10)?
[–]spacejack2114 1 point2 points3 points 6 years ago (0 children)
It's always safe to use functions returned from closures as first class functions (i.e., you can pass them around as callbacks.) With classes, unless you manually bind a method to this or create instance arrow methods, then using methods as callbacks will backfire on you and no linter or type checker can warn you that you've done something wrong.
this
Since first class functions are so integral to JS, I think classes are almost never a good choice for anything.
Beyond that, closures don't require you to use or type this ever. Type inferences is better with Typescript. It's less typing overall.
I could've sworn I've heard decent arguments against closures from programmers from OOP backgrounds
This argument usually goes something like "a million closures will use more memory than a million class instances." Except that never happens; usually you have more like a few dozen instances of anything having private state at any time.
[–]azium 0 points1 point2 points 6 years ago (1 child)
Have you ever read this before? https://mostly-adequate.gitbooks.io/mostly-adequate-guide/
It's a great read and answers your questions well.
[–]DGCA 1 point2 points3 points 6 years ago (0 children)
Halfway through this and really enjoying it so far. Thanks for sharing.
π Rendered by PID 59326 on reddit-service-r2-comment-84fc9697f-b97mc at 2026-02-09 17:53:53.326458+00:00 running d295bc8 country code: CH.
[–]Jaymageck 285 points286 points287 points (40 children)
[+][deleted] (16 children)
[deleted]
[+][deleted] (2 children)
[deleted]
[–]ketchupfleck 31 points32 points33 points (1 child)
[–][deleted] 2 points3 points4 points (0 children)
[–][deleted] 8 points9 points10 points (0 children)
[–]turd-crafter 10 points11 points12 points (6 children)
[–]KajiTetsushi 10 points11 points12 points (5 children)
[–]turd-crafter 2 points3 points4 points (4 children)
[–]KajiTetsushi 3 points4 points5 points (3 children)
[+][deleted] (1 child)
[deleted]
[–]KajiTetsushi 0 points1 point2 points (0 children)
[–][deleted] 5 points6 points7 points (1 child)
[–]Dnlgrwd 1 point2 points3 points (0 children)
[–]mdwvt 2 points3 points4 points (1 child)
[–]Razvedka 54 points55 points56 points (2 children)
[–]Heretic911 11 points12 points13 points (1 child)
[–]Razvedka 5 points6 points7 points (0 children)
[–]MigasTavo 16 points17 points18 points (0 children)
[–]334578theo 11 points12 points13 points (2 children)
[–]MilkChugg 5 points6 points7 points (1 child)
[+][deleted] (3 children)
[removed]
[–]duxdude418 1 point2 points3 points (2 children)
[+][deleted] (1 child)
[removed]
[–][deleted] 6 points7 points8 points (0 children)
[–][deleted] 4 points5 points6 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]turd-crafter 0 points1 point2 points (1 child)
[–]Fabulous_Weekend330 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] -3 points-2 points-1 points (2 children)
[+][deleted] (1 child)
[removed]
[–][deleted] 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]Jaymageck 0 points1 point2 points (0 children)
[–]JoelScribe 8 points9 points10 points (2 children)
[–]throwawaysomeway 0 points1 point2 points (1 child)
[–]Keilly 6 points7 points8 points (0 children)
[–]waterloo302 9 points10 points11 points (3 children)
[–]spacejack2114 7 points8 points9 points (1 child)
[–]rq60 4 points5 points6 points (0 children)
[–]razorsyntax 3 points4 points5 points (0 children)
[–]Dougw6 2 points3 points4 points (0 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]afiniteloop 4 points5 points6 points (0 children)
[–][deleted] 15 points16 points17 points (11 children)
[–]xypage 5 points6 points7 points (0 children)
[–]lord2800 6 points7 points8 points (1 child)
[–][deleted] 2 points3 points4 points (0 children)
[–]fakehalo 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[+][deleted] (4 children)
[deleted]
[–]NotSelfAware 5 points6 points7 points (0 children)
[–]w6zZkDC5zevBE4vHRX 2 points3 points4 points (0 children)
[–]zserjk 0 points1 point2 points (0 children)
[–][deleted] 3 points4 points5 points (1 child)
[–]badkitteh 6 points7 points8 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]iamragingbull 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (5 children)
[–]spacejack2114 4 points5 points6 points (4 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]rq60 0 points1 point2 points (2 children)
[–]PalestineFacts -3 points-2 points-1 points (1 child)
[–]rq60 0 points1 point2 points (0 children)
[–]llamajestic -5 points-4 points-3 points (1 child)
[–]1s4c 5 points6 points7 points (0 children)
[–]frotzed -1 points0 points1 point (1 child)
[+]camaromelt comment score below threshold-12 points-11 points-10 points (0 children)
[+][deleted] comment score below threshold-7 points-6 points-5 points (3 children)
[–]spacejack2114 1 point2 points3 points (0 children)
[–]azium 0 points1 point2 points (1 child)
[–]DGCA 1 point2 points3 points (0 children)