Closure Scopes

Closing isn’t over if something has been closed over

Charles Hughes
2 min readMar 28, 2014

This is part five of a five part series. For more context see the previous four posts: Understanding Function Objects In JavaScript, What is “this”?, Bind, call, and apply. Oh my!, and Scopes in JavaScript

Our final subject in our whirlwind blog series is about closure scopes. If you read my previous post that explained scopes in general, you might remember that I mentioned that, most of the time, function scopes are garbage collected after a function closes out. Closure scopes are the exception to this rule. So under what conditions can this happen? Here is a small example:

var parentFun = function(){
var x = 0;
var innerFun = function(){
return x++;
};
return innerFun;
};
var func = parentFun();
func(); // returns 0
func(); // returns 1

As complicated as it seems, this is the simplest example of closure scopes I could think of. So what is going on here? Well, first we have a function called parentFun that contains within it a variable definition x, a function definition innerFun, and a return statement returning the function innerFun. If we look at the definition of innerFun, it simply returns the value of the variable x that is defined in the parent function scope. The special thing here is that if we use the function returned by parent, the value of x is retained despite it being defined in a function that has returned! Here we returned a function that simply refers to a variable defined in parentFun, not the variable itself. Yet we still seem to have retained the variable originally defined in a function scope that has closed out. This is the magic of closure scopes.

The rule is that if a function definition refers to a variable defined outside of its own scope, that environment variable is “closed over” and a reference to that value in memory is kept for that function object as long as it exists in the system.

And that is about it! Closure scopes are actually pretty simple once you understand the other concepts that they are built on top of well. I think that the reason a lot of people have trouble with closure scopes is that they don’t have a precise understanding of scopes in general. It is really easy to gain a general intuition about scopes without truly understanding what they do or how they work.

Thanks for reading the series if you did! I had a lot of fun writing it, and I hope you enjoyed reading it! ☺

This is part five of a five part series (1, 2, 3, 4, 5).

--

--