Dec 3, 2015
In this example, we nest a few self executing functions to see how this relationship works.
So, What’s a Closure.
Now, Why Should You Care
Just tacking a new name onto something you’ve been using already isn’t all that useful, so why are we here? Closures can be manipulated to solve countless arrays of interesting programming problems. In particular, they are fantastic for…
- Logic Organization
- Function and Variable Privacy
- Removing Redundant Function Arguments
- Reducing Namespace Pollution
I don’t know about you, but I’ve never enjoyed reading math related code. I love logic, and the descriptive nature of math, but numbers, not so much. So functions like this, while understandable, would be much better served with some good old self documenting code.
Your first instinct would probably be to make a few variables to isolate the results of certain math heavy statements.
Though much easier to read, we have now introduced state to our function. While not too much of a big deal for such a small piece of logic, a more convoluted example may get very difficult to keep track of. In those cases it may be desirable to break things down into smaller functions in exchange for some added stability.
Rather than keeping track of state throughout the call stack, we can now reason about our code in much smaller and declarative chunks.
The Bad News
Declaring nested functions is always dangerous and should be done with caution. Each function you declare is a new and unique object, carrying the risk of potential performance issues.
For example, our square root function could cripple an application if it needs to iterate over millions of items. Whenever iteration or performance in consideration, always be careful before nesting functions.
Function and Variable Privacy
Closures are what make this tick. We use one self invoking function to create a new scope. And return only what we want to be public from that inner scope.
Hello World has access to the speak function inside, but both
world are private.
Removing Redundant Function Arguments
Have you ever had a series of functions that pass each other arguments in a chain. You know, like this?
This is a clear indicator of one of two things. Your code requires state and belongs in a class or module like structure or you needs to share arguments within a parent function
Since closures let your functions access the parent’s scope, we can use this to cut down on redundant arguments.
This results in code that isn’t quite as brittle and redundant as before.
The private nature of function scopes make closures prime candidates from avoiding global namespace hell.
Here, the hello variable is being overwritten in our main.js file. When your application includes many open source libraries, it’s possible to have variables in the global namespace that you may not be aware of.
This is where Immediately Invoking Function Expressions (IIFE) come in to play. Or, we can just call it a closure!