- Feb 21, 2013
- 0
- by A2 Dev Team
If you’ve followed the world of JavaScript development at all over the past few years, chances are you’ve heard the term closure thrown around a lot. You may have some idea of what it means; chances are you associate it with anonymous functions treated as first class citizens, but you may not feel you have the definition nailed down. The good news is, you’re on the right track.
The one sentence explanation is this; closures are functions which have access to the environment in which they are created. That means, when a function is created inside of another function, then returned outside of it, it still knows about the values of the variables within the function that created it. Clear as mud right?
Let’s illustrate it with some JavaScript:
var foo = function spawn_a_closure () {
var enclosed_variable = ‘something’;
var my_closure = function () {
if(enclosed_variable === ‘something’) { return true; }
return false;
}
setTimeout(function () { enclosed_variable = ‘something else’; }, 5000);
return my_closure;
}
So what does that code do? Well as the function names indicate, it creates a closure and returns it. Because of the special nature of closures, it will return true for 5 seconds until our setTimeout function runs, and the closure will return false thereafter. The closure is special because it has access to the value of enclosed_variable even though we’ve left the scope of that function. The closure still has reference to it because of the special nature of closures. So it not only remembers the value of that variable at the time the closure was created, it has access to it and knows when that variable is later changed by our setTimeout function. If you’d like to test that code you can copy and paste it into the your browser’s JavaScript console and then invoke foo repeatedly (by entering foo(); on the console) and you will see it return true for 5 seconds then switch over to false.
This is just the simplest illustration of a closure. There are amazing, powerful things you can do with them and learning to make use of them will drastically change the way you approach JavaScript or any other language that supports them.