re: Explain Closures to me like I am five VIEW POST

FULL DISCUSSION
 

Your mom has offered to make you cookies whenever you want. All you have to do is bring her the ingredients. This sounds great, but what if you just want a couple cookies? You'll need to get the ingredients, bring them to your mom, and she'll bake a large batch of one kind. It'd be much nicer to have a few cookies on demand, and different kinds.

In your bedroom you have a magic lamp. You rub it and out pops a genie. You explain the problem and he gives you a solution. He creates a large magic box in the kitchen. He tells you how it works. You put all the ingredients in for chocolate chip cookies and your mom puts the recipe in. From the bottom pops out another much smaller box. It has a button on it and the label "Chocolate chip". You press the button and after a few moments and weird sounds a few chocolate chip cookies pop out of a slot on the side.

You're excited. In the big magic box you now add ingredients for oatmeal cookies and your mom throws in the recipe. Out the bottom pops a box labelled "Oatmeal". You press the button and get a few oatmeal cookies. Just to be certain you pres the "Chocolate Chip" button again and sure enough, it's still producing chocolate chip cookies.

You realize you can take these boxes wherever you want. You create a "Shortbread" box for your room. You make a "Ginger Snap" box by the TV. For good measure you create a "Peanut Butter" box for the back of your bike. This is great!

You get a bit curious though, how do they work? You ask the genie. He waves his hands a lot and calls the little box a "closure". Basically it's a combination of the recipe (instructions) and ingredients (data) needed to make some cookies. It might even be somehow magically connected to the big box in the kitchen, where the stove is, but you don't need to know for sure. Really, how it was created doesn't interest you anymore so long as the little box keeps creating cookies.

For a non-ELI5 explanation please see What is a closure

code of conduct - report abuse