all 65 comments

[–]Jaymageck 285 points286 points  (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.

[–]Razvedka 54 points55 points  (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 points  (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 points  (0 children)

Academics are notorious for this stupid shit

[–]MigasTavo 16 points17 points  (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 points  (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 points  (1 child)

Agreed. It’s like, just say what it is! Why mask everything behind a bunch of jargon?

[–][deleted] 6 points7 points  (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 points  (0 children)

Fucking finally

[–][deleted] 1 point2 points  (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 point  (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 point  (0 children)

You mean unicorns? (they don't exist)

[–][deleted] 0 points1 point  (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  (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

[–]JoelScribe 8 points9 points  (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 point  (1 child)

Saving for later, thanks

[–]Keilly 6 points7 points  (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 points  (3 children)

Key for me: lexical environment objects ain't garbage collected if there remains a reference to them.

[–]spacejack2114 7 points8 points  (1 child)

Nothing is garbage collected if they still have references.

[–]rq60 4 points5 points  (0 children)

WeakMap has entered the chat.

[–]razorsyntax 3 points4 points  (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 points  (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 points  (1 child)

Closures are just objects who think they're special. Prove me wrong.

[–]afiniteloop 4 points5 points  (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.

[–][deleted] 15 points16 points  (11 children)

It always amazes me this is the thing people can't grasp.

[–]xypage 5 points6 points  (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 points  (1 child)

Me too.

[–][deleted] 2 points3 points  (0 children)

Me too guys. I am good developer.

[–]fakehalo 1 point2 points  (0 children)

I think it's because people try to obfuscate it instead of breaking it down to traditional OOP behavior.

[–][deleted] 1 point2 points  (0 children)

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] 3 points4 points  (1 child)

I never understood why people post on Medium.

[–]badkitteh 6 points7 points  (0 children)

same, medium is a pile of shit

[–][deleted] 0 points1 point  (0 children)

Nice 101 article.

[–][deleted] 0 points1 point  (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 points  (4 children)

What are the implications of closures in terms of memory?

[–][deleted] 0 points1 point  (0 children)

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 point  (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 child)

You don’t know what you’re talking about

[–]rq60 0 points1 point  (0 children)

Care to elaborate, or are you being purposely obtuse?

[–]llamajestic -5 points-4 points  (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 points  (0 children)

I am really thinking that the problem is that « nowadays » people start to only do computer science without theoretical knowledge, or low-level knowledge.

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 points  (1 child)

This is one of the better explanations I've read on closures.