Skip to main content

JavaScript Closures

What are closures in JavaScript?

Taken from http://jibbering.com/faq/notes/closures/:
The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodes of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s). A closure is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned. At which point it still has access to the local variables, parameters and inner function declarations of its outer function. Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.
For Example:

var x;
function foo()
{
    var i = 2;
    function bar() {
        i++;
        return i;
    }
    console.log(i); //Prints 2
    bar();
    console.log(i); //Prints 3
    x = bar;
}
foo(); //Prints 2 and 3
x(); //Now i == 4
console.log(x()); //Prints 5
foo(); //Prints 2 and 3 again



Note that bar() is an inner function that has access to foo()'s local variables.  But, the most interesting part is that after foo() returns, we can still access i by calling x().

Closures inside a for loop:
Suppose you have an list in a XHTML document.  You might want to setup an event handler that does something when you click on an item.  I'll use jQuery syntax if you don't mind.

You might be tempted to write:
var listItems = $("#list li");
for(var i = 0; i < listItems.length; i++)
    listItems.eq(i).click(function() {
        alert(i);
    });

The desired behavior is that clicking first list item would display 0, clicking the second list item would display 1, and so forth.  What actually happens, is that they all display whatever listItems.length is because that is the last known value for variable i.  Closures worked in this case, but not as desired.

Fortunately, fixing this little problem is much more trivial than one might think.  Simply create another scope level!!!  Check this out...


var listItems = $("#list li");
for(var i = 0; i < listItems.length; i++)
    listItems.eq(i).click(function(i2) {
        return
function() {
            alert(i2);
        };
    }(i));

In this case, I am passing the value of i into a new inner function (gray) that returns the former function in the previous example (red).  i2 is now in a new scope level and gets a new memory location for each iteration of the for loop.  For clarity, I have changed the variable name to i2 in the inner function, but you could also call it i.  Problem solved.

This is EXTREMELY useful in Node.JS since there are almost no synchronous, blocking function calls; rather, any I/O request or other "blocking" request is made using a callback function.

Comments

Popular posts from this blog

Developing a lightweight WebSocket library

Late in 2016, I began development on a lightweight, isomorphic WebSocket library for Node.js called ws-wrapper .  Today, this library is stable and has been successfully used in many production apps. Why?  What about socket.io ?  In my opinion, socket.io and its dependencies are way too heavy .  Now that the year is 2018, this couldn't be more true.  Modern browsers have native WebSocket support meaning that all of the transports built into the socket.io project are just dead weight.  On the other hand, ws-wrapper and its dependencies weigh about 3 KB when minified and gzipped.  Similarly, ws-wrapper consists of about 500 lines of code; whereas, socket.io consists of thousands of lines of code.  As Dijkstra once famously said: "Simplicity is prerequisite for reliability." ws-wrapper also provides a few more features out of the box.  The API exposes a two-way, Promise-based request/response interface.  That is, clients can request dat...

Wedding Prediction - October, 2013

Carla and I are planning on getting married sometime in October next year.  We need to pick a date, and that decision may  involve some science and mathematics.  :) For example, we want the weather to be nice.  To be more precise, we'd like the high temperature for the wedding day to be between 60 and 80 degrees Fahrenheit.  Obviously, we have both lived in Ohio our entire lives, and we have a pretty good idea of what the weather will be like.  We both hypothesised that October was a "hit or miss" sort of month; it could be cold, or it could be nice. But, for me, a simple hypothesis was not enough; I really wanted to know the probabilities of decent weather based on historical weather data.  Many websites on the Internet (i.e. almanac.com) charge you to review historical weather data, but Carla and I discovered a cool page on cleveland.com that provided exactly what we wanted.  I loaded the historical temperature data from 1903 to 2011 f...

Data Persistence in Various Databases

This blog post will cover the varying levels of data caching and data persistence provided by various operating systems and database systems. Cache  - A device placed in front of another storage device that is used for temporary storage of data.  The use of a hardware cache is often transparent to the end user and is generally smaller, faster, and less persistent than the backed storage device.  Rather than reading/writing from/to a slower storage device (i.e. a hard disk), we read/write from/to the cache (i.e. RAM, NVRAM, etc.). Reading from a cache is simple.  If the datum we requested is in the cache, we simply read it from the cache.  If not, we need to retrieve the datum from the storage device and place it into the cache (often a much slower operation). There are different policies when we write to the cache, though... Write-Through Cache Policy  - When using this policy, writing over the cache also writes over the data on the backed storage d...