JavaScript – A Different Beast, Part-5: Closures

Previous topic in this series: Scopes and Scope Chain

This is the fifth part of my tutorial on JavaScript. Focus of this series is to introduce developers who are comfortable with other programming languages like Java or C to the idiosyncrasies of JavaScript. Basic JavaScript knowledge is assumed, but is not necessary as the code samples are simple and self-explanatory.


Topics:

  1. A different beast
  2. Types and Type Conversion
  3. Functions
  4. Scopes and Scope Chain
  5. Closures
  6. Objects without Classes
  7. Inheritance without Classes
  8. Arrays, Maps and the for..each loop
  9. Literals and JSON
  10. Dynamic Programming, Exceptions and Module Pattern

Closures are one of the most esoteric features of JavaScript. Effective usage of closures is a crucial skill needed for web programmers these days. Incidentally, most programmers use them by accident, as we will see shortly. Unfortunately, an in-depth knowledge of the language internals is required for a proper understanding of closures. What I am going to attempt here is an alternate explanation where we will just focus on the effects of some code snippets rather than understanding how it really works. In short, we will see how to make closures work for you, but we won’t really cover how closures work.

Let’s take a simple example first. Code-2-10 below shows a piece of code with a closure.

//Code – 2.10:  A simple closure
function foo() {
    var x = 'Hello'; //local variable
    function bar() { //local function
         console.log(x); //local function referring to local variable
    };
    return bar; //returning the function
}

var func = foo(); //get the inner function
func(); //invoke it! It prints ‘Hello’

The funny thing to note here is that the variable x along with its binding to value ‘Hello’ was still alive even after the function foo had exited! How do you explain that? Answer is ‘Closures’.  Let’s look at the scope chain for this scenario to understand this. Left part of the figure below shows the scope chain when function foo is about to execute the last line viz. ‘return bar’;

Closure Illustrated (Code-2.10)
Closure Illustrated (Code-2.10)

In the figure, the functions and scopes are shown as ovals and variables are shown in rectangles. Each scope is dependent on its surrounding scope and hence, function bar can access the variable x. When a function-execution is over its scope will also terminate. But in this case, since the function foo is returning the function bar to the global scope, bar and its surrounding scope cannot be destroyed and therefore will remain with function bar. Such an in-memory construct consisting of a function and its surrounding scope caused by returning inner functions from outer functions is called a closure. Right part of the figure below shows the scopes after the closure is formed. Variable func in the global scope is now pointing to the closure bar.

In programming language theory, a free variable is a variable which does not have any value bound to it- not even the null value whereas a bound variable has values assigned to it.  The set of bindings for an instruction in that language is actually the scope for that instruction.

Closures are formed when the scope chain of an object survives outside its creation scope. This has the interesting property that some of the variables are bound in the scope chain whereas others are free. (See sidebar) Code-2.11 shows a closure with bound and free variables.

//Code – 2.11:  Function factory
function makeAdder(x) {
      return function(y) { //returning a closure, where x is bound and y is free
            return x + y;
      };
}

var add5 = makeAdder(5); //add5 is a closure where x=5
var add10 = makeAdder(10); //add10 is a closure where x=10
print(add5(2));  // 7
print(add10(2)); // 12

Really cool, huh? But not very useful, is it? Let’s see some practical usages.

About these ads

About Rahul Mohan

Technical researcher interested in model-driven development of enterprise business applications. Passionate about web technologies and a huge admirer of open-source especially in the Java landscape. When I am not doing any of the above you can find me with my camera (www.flickr.com/photos/rahulmohan/) or listening to music. (In fact, the title of the blog is inspired by Led Zeppelin's Physical Graffiti. )

Posted on May 15, 2011, in JavaScript, Tutorial and tagged , , , , , , , , . Bookmark the permalink. 4 Comments.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: