JavaScript & Python Closures

After a hard day of climbing in the canyon my fellow climbing/coder friend Tim started to tell me about a feature of JavaScript he had just started to use called Closures. Even though I have written thousands of lines of JavaScript I had never heard of Closures. As a self proclaimed eternal student I was intrigued with what he was telling me.

Turns out that Closures are generally considered to be JavaScripts most advanced and useful feature, and hence, is worthy of a blog post :-). As a C++ coder I like to think of Closures as a method with a privately malloc’d stack that is persistent across multiple invocations. As a Python coder I like to think of Closures as a method object with a preserved variable environment. Regardless of how you want to think about them, Closures allow us to redefine how we approach coding up methods.

Take the following simple JS example. Here, we are creating a very simple incrementer. The method inc() takes a starting value and returns a method that simply adds one to the start value (but not until its actually executed in the loop below).

function inc(start){
	var i = start;
	return function() { i = i + 1; document.write(i); }

addOne = inc(0)
for (i = 0; i < 10; ++i){
// prints 12345678910

I’m probably just super geeky but I find this feature of the language very cool. Turns out we can also do the same thing with Python.

#Works with Python 3.x only
def inc(start):
    y = start
    def adder():
        nonlocal y
        y += 1
        print y
        return y
    return adder
addOne = inc(0)
x = 0
for x in range(10):
#prints 12345678910

The ramifications of Closures to popular programming languages are still in its infancy even though the concept has been around for decades (adding them to Java has been a debate for years). It will be extremely interesting to see how the wide spread adoption of Closures will ultimately impact our coding habits in the near future.