Closure is a programming technique, that (much like recursion) is often over-complicated and can cause unnecessary headaches. However, don’t let the intimidating lexical syntax scare you away. You can start down the closures internet rabbit hole soon (trust me, there’s enough to keep you busy for a few weeks), but first, let’s grasp the basic concept.
At its simplest, a closure is a function that returns another function. However, there is a bit more nuance to it — the inner function’s utilization of something that’s been defined in the outer scope. The inner function is a local variable to the outer function. When a function is defined inside of another function, the inner function has access to the variables and scope of the outer function. Closure occurs when an inner scope accesses the outer scope once the outer scope is done executing. The inner function “closes over” the scope of the outer function, thus creating a closure.
To put it metaphorically, think of the outer, or parent, function as a “pregnant” function, and within, there’s an inner “pregnant” function that returns a baby. When that outer function is invoked, the baby is born. Say that the baby object holds attributes for eye color or hair color. The eye color could be passed in as an argument to the parent function, and the hair color could be passed into the baby function as an argument. Either way, the baby function would have access to those parameters.
Now for a more tangible, real-life example. We’re working on a racing app. Every time a racer crosses the finish line, they receive a message — either that they’re the winner, or they lost. The message displayed ultimately depends on the order of the individual racer’s finish — we want the first to finish to receive the winning message, and then all the rest get the losers’ notification. We can use a closure to accomplish that!
Try this out for yourself to see the results!
Hopefully this has helped deepen your understanding of closures. Thanks for reading.