Monday, May 10, 2010

Intuition When Using Closures

I got into a debate with somebody in #javascript today regarding closures: how they work, how they should work, and are they intuitive. This person had run into a problem similar to the one I posted about earlier. In any case, as the discussion was coming to a close, I created some examples which somebody suggested I blog about. Let's start with a simple piece of code that more or less shows the original problem.

var i = 0; 
el.onclick = function() { print(i); }; 

In the above example what will be printed? This person argued that, intuitively, "0" should be printed. Of course the correct answer is that "1" will be printed. I can understand how this may be confusing to someone new to Javascript. However, take another example:

var i = 0;
var func = function() { i++; };

If I were to show this piece of code to someone, they would probably say that it makes sense. Of couse "1" will be printed. It is intuitive (and correct). Following that line of reasoning:

var i = 0;
var func = function() { print(i); };

This code also seems to make sense, especially in light of the previous example. The only real difference is that this example reads/prints the variable, and the previous one modified the variable. In both cases "1" will be printed.

Now we're back to the original code:

var i = 0; 
el.onclick = function() { print(i); }; 

Note that the only difference between this piece of code and the previous one is when the function is executed. In one the function is executed right away, in the other the function is executed as a click handler. In both cases i++ occurs first and in both cases "1" is printed. This is consistent behavior and somewhat shows how closures can morph from something which "just makes sense" into something that isn't quite as intuitive.

The reason for this behavior is that closures work by pointing to the original variable by reference, if you will, not by value - even for primitives. So when the anonymous function runs, i is still pointing back to the original i which has been incremented to 1.


  1. Thanks for writing this up, James. This is a great explanation of something that beginners often trip over.

    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Online Training from India . or learn thru JavaScript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

  2. patriots jerseys,
    saints jerseys,
    karen millen uk,
    air jordan 11 free shipping,
    hollister canada,
    hollister uk,
    tods outlet,
    air jordan 4 free shipping,
    pandora jewelry,
    coach outlet online,
    tiffany and co,
    prada outlet,
    ravens jerseys,
    supra shoes,
    hogan,hogan outlet,scarpe hogan,hogan sito ufficiale,hogan interactive
    michael kors outlet,
    juicy couture tracksuit,
    chicago bulls,
    jets jersey,

  3. This blog is so nice to me. I will continue to come here again and again. Visit my link as well. Good luck
    cara menggugurkan kandungan

  4. تمتع باقوي العروض الهائلة ومميزة من شركة رش مبيدات بالدمام والتي تعمل علي خدمات رش الحشرات وطرق المكافحة وابادتها تماما.

  5. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout obat pembesar penis

  6. There are times that you can even get affirmed inside minutes and get the cash you require inside hours. You can in a split second pay your bills in a day or two. Auto title credits give you the cash you require when you require it! car title loans chicago

  7. My first online casino solely best casino in which I played. Just want to highlight a very beautiful design and convenience and beauty in all games. The presence of public tables testifies first of all to casino honesty - nobody twists the roulette wheel specially - at least =).

  8. Obat Viagra merupakan obat kuat yang paling populer di dunia . Maka dari itu tak heran jika ada oknum yang memanfaat untuk membuat produk tiruan . Viagra sangat membantu sekali bagi kaum pria , karena manfaat viagra dapat menambah rasa percaya diri saat melakukan hubungan .