02 Jul 2017
Great. We can all go home now.
If you employ the services of google to help you understand what a closure is, you will likely come across code examples with nested functions. There is a valid reason for this, as these functions help to demonstrate how different environments can change our closures, but the definition above explains that ALL functions are closures. We don’t have to get fancy to explain what the hell this thing really is.
In my first example, I am declaring a variable, name, with the value of my name. Then, I am writing a function, printName, that console logs the name variable that I declared above it. If you test this out yourself, you will see that it works.
It may seem obvious that this works but — look closely — we never called our printName function with an argument. What’s remarkable about what this function is doing is the very thing that makes it a closure. Our function was able to grab the name variable declared outside of itself, and within the global environment, to complete our operation.
Understanding closures is also important for understanding the mechanics of partial application and currying. When we pass arguments into functions that return functions, our return functions, or closures, are aware of these arguments.
Let’s examine the code below.
Here, I am defining a function, multiplyNumbers, that accepts two numbers and returns their product. I have written this function to return another function in the case that it only receives one argument. This return function, or closure, can access the first variable that we gave our outer function, multiplyNumbers, and complete our operation. At the bottom of the screenshot, you can see that both ways (passing both arguments into the outer function AND passing the first argument to the outer function and the second to the inner function) return the same result.
We can supply our outer function only one argument and name the resulting function (see below).
I believe that the power of closures truly shines here. Our named methods, multiplyByFive and multiplyByFour, were birthed by the same function, multiplyNumbers. They only differ in the environment scope that they refer to. The first argument for multiplyByFive is still 5, even after the creation of an additional function, multiplyByFour, that takes in a different first argument. Pretty cool, right?