Understand JavaScript Closures With Ease

February 2 Last Year

Closures are lovely and reliably serviceable: They allow programmers to program creatively, expressively, and concisely. They are used frequently in JavaScript and, no matter your JavaScript skill level, you will no doubt encounter them. Sure, closures might appear complex and beyond your scope, but after reading this article, closures will be much more easily understood and more appealing for usage in your everyday JavaScript programming.

This is a relatively short (and sweet :) ) post on the details of closures in JavaScript. You should be familiar with JavaScript variable scope before you read further, because to understand closures you must understand JavaScript’s variable scope.

What is a closure?
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.

You create a closure by adding a function inside another function.
A Basic Example of Closures in JavaScript:

function showName (firstName, lastName) {

var nameIntro = "Your name is ";
    // this inner function has access to the outer function's variables, including the parameter
function makeFullName () {
        
return nameIntro + firstName + " " + lastName;
    
}

return makeFullName ();

}


showName ("Michael", "Jackson"); // Your name is Michael Jackson


Closures are used extensively in Node.js; they are workhorses in Node.js’ asynchronous, non-blocking architecture. Closures are also frequently used in jQuery and just about every piece of JavaScript code you read.
A Classic jQuery Example of Closures:

$(function() {

var selections = []; 
$(".niners").click(function() { // this closure has access to the selections variable
selections.push (this.prop("name")); // update the selections variable in the outer function's scope
});

});

Closures’ Rules and Side Effects

  1. Closures have access to the outer function’s variable even after the outer function returns:
    One of the most important and ticklish features with closures is that the inner function still has access to the outer function’s variables even after the outer function has returned. Yep, you read that correctly. When functions in JavaScript execute, they use the same scope chain that was in effect when they were created. This means that even after the outer function has returned, the inner function still has access to the outer function’s variables. Therefore, you can call the inner function later in your program. This example demonstrates:

    function celebrityName (firstName) {
        var nameIntro = "This celebrity is ";
        // this inner function has access to the outer function's variables, including the parameter
       function lastName (theLastName) {
            return nameIntro + firstName + " " + theLastName;
        }
        return lastName;
    }
    
    var mjName = celebrityName ("Michael"); // At this juncture, the celebrityName outer function has returned.
    
    // The closure (lastName) is called here after the outer function has returned above
    // Yet, the closure still has access to the outer function's variables and parameter
    mjName ("Jackson"); // This celebrity is Michael Jackson

  2. Closures store references to the outer function’s variables; they do not store the actual value. 
Closures get more interesting when the value of the outer function’s variable changes before the closure is called. And this powerful feature can be harnessed in creative ways, such as this private variables example first demonstrated by Douglas Crockford:

    function celebrityID () {
        var celebrityID = 999;
        // We are returning an object with some inner functions
        // All the inner functions have access to the outer function's variables
        return {
            getID: function ()  {
                // This inner function will return the UPDATED celebrityID variable
                // It will return the current value of celebrityID, even after the changeTheID function changes it
              return celebrityID;
            },
            setID: function (theNewID)  {
                // This inner function will change the outer function's variable anytime
                celebrityID = theNewID;
            }
        }
    
    }
    
    var mjID = celebrityID (); // At this juncture, the celebrityID outer function has returned.
    mjID.getID(); // 999
    mjID.setID(567); // Changes the outer function's variable
    mjID.getID(); // 567: It returns the updated celebrityId variable

  3. Closures Gone Awry
    
Because closures have access to the updated values of the outer function’s variables, they can also lead to bugs when the outer function’s variable changes with a for loop. Thus:

    // This example is explained in detail below (just after this code box).
    function celebrityIDCreator (theCelebrities) {
        var i;
        var uniqueID = 100;
        for (i = 0; i < theCelebrities.length; i++) {
          theCelebrities[i]["id"] = function ()  {
            return uniqueID + i;
          }
        }
        
        return theCelebrities;
    }
    
    var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];
    
    var createIdForActionCelebs = celebrityIDCreator (actionCelebs);
    
    var stalloneID = createIdForActionCelebs [0];

console.log(stalloneID.id()); // 103

    In the preceding example, by the time the anonymous functions are called, the value of i is 3 (the length of the array and then it increments). The number 3 was added to the uniqueID to create 103 for ALL the celebritiesID. So every position in the returned array get id = 103, instead of the intended 100, 101, 102.

    The reason this happened was because, as we have discussed in the previous example, the closure (the anonymous function in this example) has access to the outer function’s variables by reference, not by value. So just as the previous example showed that we can access the updated variable with the closure, this example similarly accessed the i variable when it was changed, since the outer function runs the entire for loop and returns the last value of i, which is 103.

    To fix this side effect (bug) in closures, you can use an Immediately Invoked Function Expression (IIFE), such as the following:

    function celebrityIDCreator (theCelebrities) {
        var i;
        var uniqueID = 100;
        for (i = 0; i < theCelebrities.length; i++) {
            theCelebrities[i]["id"] = function (j)  { // the j parametric variable is the i passed in on invocation of this IIFE
                return function () {
                    return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array
                } () // BY adding () at the end of this function, we are executing it immediately and returning just the value of uniqueID + j, instead of returning a function.
            } (i); // immediately invoke the function passing the i variable as a parameter
        }
    
        return theCelebrities;
    }
    
    var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];
    
    var createIdForActionCelebs = celebrityIDCreator (actionCelebs);
    
    var stalloneID = createIdForActionCelebs [0];
    
console.log(stalloneID.id); // 100
    
    var cruiseID = createIdForActionCelebs [1];
console.log(cruiseID.id); // 101

Check back on February 7th for a quiz on JavaScript Closures.

Thanks for your time; please come back soon. Email me here: javascriptissexy at gmail email, or use the contact form.

142 Comments

  1. Nimesh

    Thanks for the great post. I am bookmarking your website. A sexy collection of javascript tutorials.

  2. pradeep

    very helpful

  3. Lixiang

    Good post, It makes me feel Javascript is so sexy and interesting.

  4. Roberto

    Sorry man, I really don’t get the example on the first rule,
    when you say:

    mjName (“Jackson”); // This celebrity is Michael Jackson


    how are you calling the inner function there?

    • No need to be sorry, Roberto, I understand how this part is confusing.

      Here is the explanation.
      The celebrityName function returns a function; the function it returns is the lastName inner function.
      So when we do:
      var mjName = celebrityName (“Michael”);
      The mjName variable now contains the lastName inner function that was returned when we called celebrityName (). And the inner function has all the variables, including the name “Michael” that was passed into the celebrityName function.

      To prove that the mjName variable contains the lasName function, we can do this:

      console.log (mjName);
      
      // The output is this:
      function lastName(theLastName) {
              return nameIntro + firstName + " " + theLastName;
          }
      

      So mjName is a function expression: it is a variable with a value of a function.
      Now, all we have to do to call the function stored in mjName is add the parentheses () to execute the function, like this:
      mjName (); //When it executes, the following line from the lastName inner function runs;
      return nameIntro + firstName + ” ” + theLastName;
      And this is why the output is: “This celebrity is Michael Jackson”
      When we do mjName (“Jackson”);

      • Roberto

        Getting there!! but WOW! thanks for taking the time to write such a long and clear answer! I’m wrapping my head around the last one now.

        It’s weird though being a JavaScript Blog you dont have client side validation on the comments form. ;)

        • You are welcome.

          I haven’t thought about the client-side form validation until you mentioned it, so I just added it. Thanks for the tip. We helped each other out :)

        • Vineet Sajwan

          Hey Roberto,
          Its quite amazing that I have same two doubts, one is mjName thing and other absence of javascript form validation on a such a SEXY javascript tutorial site.

          Thanks Richard Bovell for sharing your valuable knowledge.

      • Christopher

        This was *profoundly* helpful to me. Thank you so much for taking the time to reply so thoroughly.

      • Thank you so much for this comment. I’ve been trying to understand clojures for a few days now and the fact that it was returning the function was the missing piece for me, I feel like all the code I’ve pored over just suddenly started to make sense.

      • Pravin Waychal

        Very Helpful and clear explanation. Thanks so much!

      • andy

        everyone trying to understand closures should read this question and answer.

      • jackson

        Thanks for this really helpful reply. Pointing out that the container function returns the inner function was key for me.

        Although after typing out the example, I noticed that printing out mjName doesn’t actually show the function.
        console.log(mjName); //prints [Function: lastname]

        To show the actual function I had to use the prototype method of the function object:

        console.log( mjName.toString() ); //prints function source

  5. Juan

    This site rocks man!! Thanks for sharing your knowledge in an easy way. Saludos desde Argentina

  6. ali

    i have one question about the following.
    theCelebrities[i]["id"] = function (j) { // the j parametric variable is the i passed in on invocation of this IIFE

    how does it here know the j should take the value of the current i ,maybe i am missing something obvious in here:)

    many thanks

  7. For the CelebrityIdCreator example, could you also use:

    theCelebrities[i]["id"] = i;

    So that the value is set right then, rather than have “id” be a function?

    • Very good question, Jason.

      To do that, we can make one change:
      Instead of returning a function, we can go ahead and call the function (execute it immediately) and return the uniqueID + J number.

      I just updated the code in the article to store numbers in the returned array, instead of functions.

  8. Piyush

    Hi Richard,
    Awesome blog….seriously …going through your blog has made some of the difficult concepts so easy. Thanks a lot.

    Is it possible to refactor the code for removing the bug in Closure with the below way :

    theCelebrities[i]["id"] = (function () {
    return uniqueID + i;
    })();

    The one mentioned above somewht confused me at the start , so i guess this would too solve the purpose. In effect, both the code are doing the same things :) :)

    • HI Piyush,

      I am glad you were able to refactor the code to a style that works better for you. That is an important aspect of programming that is underrated. In my opinion, you should feel very comfortable with the way your code looks and reads back in your head.

      When I have some time, I will look at the code and see if it is worth refactoring.

      Thanks.

  9. Very good article. I loved your explanation really but when i saw:

    theCelebrities[i]["id"] = function (j) {
    return function () {
    return uniqueID + j;
    } ()
    } (i);

    i got uncomfortable. Because you introduce two IIFE here. And one can offer in a more complicated way as:

    theCelebrities[i]["id"] = function (j) {
    return function () {
    return function() {
    return function() {
    return function() {
    return uniqueID + j;
    }()
    }()
    }()
    } ()
    } (i);

    but these all make things more harder. I suggest to use just IIFE in a simple way as:

    theCelebrities[i]["id"] = function (j) {
    return uniqueID + j;
    } (i);

    and all these versions just use:

    theCelebrities[i]["id"] = uniqueID + j;

    ——————————————
    Besides I want to add one more thing: your first example under “Closures Gone Awry” section all ids assigned to a function but the other example(bug fixing as your phrase) just assigns numeric variable using IIFE.I think it is impossible to solve this problem with assigning function to ids.

  10. Nirmal

    Richard, this is the coolest blog on JavaScript that I ever saw! It helped me in understanding the fundamentals thoroughly. :) Thanks!

  11. Evox

    - In example 2, why we have to add return before get and set function.

    - why it have to include return before function and value, can I write it with out return

    - Is the inner function excute and return separately from outer function?

    Thanks you

    • You can reformat the code to not return an object with the methods, but then you will have to change the celebrityID function and make it an object. And is you do, there will be no reason to assign it to another variable to use the closure with references to the outer function’s variables.

      So the reason we used “return” to return an object in the celebrityID function is precisely because of the closure and accessing the outer function’s variables later.

  12. WebGyver

    First of all, thanks for this article. I greatly appreciate the time you took to work on the article itself but also on answers to questions.

    I have a problem with the celebrityName example that returns a function. No matter how hard I try, I can only get the first name back. Instead of a lastName, I only get a 0.

    I have set this up at http://jsfiddle.net/MmDvz/ if anybody else wants to help me see the errors of my ways.

    Thank you for any help anyone could offer.

    • Ecovox

      I think the mjName(“Miller”); was return and destroyed before you call it. try this: $(‘#name’).html(mjName(“Miller”));.

      I’m not sure why it be like this, maybe a concat method from primitive wrapper was call to produce it, after it is call, it will destroy.

      sorry for my English.

    • You have everything correct except you need to call mjName as a function, as Ecovox correctly pointed out below.

      
      /* The mjName variable is being assigned a function, which is the function returned by your celebrityName function. 
      */
      var mjName = celebrityName("Mike");
      // So you must call mjName like this:
      $('#name').html(mjName("Miller"));
      
      // Instead of like this
      $('#name').html(mjName);
      

      This line below by itself (which you have in your code) is not displaying anything to the screen or on the page because you are not logging (console.log) it to the console or displaying the results to the page:

      
      mjName("Miller");
      

      So the bottom line is that you can do either this:

      
      console.log(mjName("Miller));
      

      Or this:

      
      $('#name').html(mjName("Miller"));
      

      Ecovox, thanks for helping out. You answer is correct.

  13. Noah Jerreel Guillen

    Your blog is really amazing. Keep it up.

  14. dineshswamy

    I like most of your articles !! Your articles stands because of one reason .. you dont give space for ads !! Nice.

  15. tanyaka

    Dear Richard, your blog is awsome and I do enjoy reading it, thank very much! Still, I have the same questinon as soncu on June 26 (may by I missed something essential). Why not to use:

    theCelebrities[i]["id"] = function (j) {
    return uniqueID + j;
    } (i);

    instead of

    theCelebrities[i]["id"] = function (j) {
    return function () {
    return uniqueID + j;
    } ()
    } (i);

    ?

    Thank you so much for your time!

    • The reason the code returns a function is because the point of closures is that the inner function has access to the outer function’s variables even after the outer function has returned, so you can continue to execute code like this: stalloneID.id(). The demonstration was about closures, which are inner functions, hence the example.

      Indeed, you can choose to not return a function and simply return the variable, but in some scenarios, you do need to return a function that you want to call later. The code shows the example of returning a function and calling that function at a later time.

      • tanyaka

        i see. thank you very much!

      • Pearce

        Hey Richard,
        I believe you are missing soncu and tanyaka’s critique. The second block of code assigns numbers to the id property of elements in the “theCelebrities” array, not functions. This trivializes the problem and makes the use of IIFE’s unnecessary. This is confusing your readers. I think the most instructive solution would be this:

        function celebrityIDCreator (theCelebrities) {
        var i;
        var uniqueID = 100;
        for (i = 0; i < theCelebrities.length; i++) {
        theCelebrities[i]["id"] = function (j) {
        return function() { // Return a function, not a number
        return uniqueID + j;
        }
        }(i)
        }

        return theCelebrities;
        }

        var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

        var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

        var stalloneID = createIdForActionCelebs [0];

console.log(stalloneID.id()); // 100

        • I must be missing something because the same code you are suggesting is what I provided in the article above: the first part of section “Closures Gone Awry.”

          • Pearce

            The code I’m suggesting has 1 IIFE as opposed to 2 (or 0). Sorry for the lack of formatting, I couldn’t figure out how other commenters did the formatted code blocks.

      • San

        Hello,
        I have also the same confusion.
        In the code if I give as follows the result as follows.
        
console.log(cruiseID.id); // 101
        
console.log(cruiseID.id()); // TypeError: stalloneID.id is not a function

        why it shows this error?
        //San

        • yes, i get the same error too. in the first part code i could call id as a function meaning id(). the second part id is no longer a function, but just a number so i couldn’t call it.

  16. sameer

    Thanks for the sexy website

    • Thanks, Sameer.

      I am hopeful the site is sexy and informative at the same time. The saying in English is “brain and brawn” :), which means sexy (or strong for male) and smart at the same time.

      I added the explanation for “brain and brawn” in case English is not your first language.

  17. For the last solution won’t just be alot easier to use bind?

    function celebrityIDCreator (theCelebrities) {
    var i;
    var uniqueID = 100;

    for (i = 0; i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = function (j) { // the j parametric variable is the i passed in on invocation of this IIFE
    return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array
    }.bind(this, i) // BY adding () at the end of this function, we are executing it immediately and returning just the value of uniqueID + j, instead of returning a function.
    }

    return theCelebrities;
    }

    var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

    var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

    var stalloneID = createIdForActionCelebs [0];
    
console.log(stalloneID.id()); // 100

    var cruiseID = createIdForActionCelebs [1];
console.log(cruiseID.id()); // 101

    • Thanks for the bind () alternative, Cosmo.

      This is why JavaScript is cool: you can always find an expressive way to execute your code, and the bind example you illustrated is perfectly fine, if you are interested in just returning the value and not a function.

      Note that in some scenarios, as I have noted above in an earlier comment, you may want to return a function, which is more versatile than returning just the value. But your solution is a wonderful addition nonetheless.

  18. Hi,

    Thanks for this great page. I’ve been pouring over it and absorbing every line. I think I have it all except the following:

    for (i = 0; i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = function (j)

    How does the value of i get passed into j if it's never explicitly told they are the same value?

    Thanks!
    Pierre

    • NM just had a facepalm moment. I was so fixated on that part of the code, I neglected to notice it was being passed in below!

    • richard/pierre,
      would appreciate if you can elaborate on this. i still don’t see the connection between the i and the j. thanks.

      • Shawn K.

        i is passed in at the end of the function like this (i). Make sure you’re reading the entire function. I also had a few minutes of not understanding how j got the value of i, but it does indeed get passed in.

  19. hiren

    Hi Richard,

    Great site. Found really helpful.
    Thank you so much.

    Hiren

  20. olivier nguyen

    Hi there, this is a great website. The suggestion I would make is that the code examples are hard to read because of the narrow width of the main column. And the indentation doesn’t help either.

    Looking forward to more posts!

  21. Ahmed

    Thanks for the post , its the best I read on Closures

    • Thank you very much for the comment, Ahmed. I am happy to hear that the article has been helpful to you.

    • Roshan

      Hello Richard,

      This is one of the best explanations that I have read. It seems like this explanation will be understood even by a 6 year old. Remembering the famous Einstein quote.

      I have subscribed and will be waiting to see more from this site.

      One quick question
      console.log(cruiseID.id);
      what is this cruiseID?

      • Thanks very much for wonderful compliment, Roshan.

        The cruiseID is the variable that will hold the value of Tom Cruise’s data. First, here is the object with all the celebrities:

        
        var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];
        

        Then we set up the array that will hold all the celebrities; we do this by executing the celebrityIDCreator function with the object we created in the line above:

        
        var createIdForActionCelebs = celebrityIDCreator (actionCelebs);
        

        And with those, we then created variables for each celebrity, so the Tom Cruise variable is this one:

        
        var cruiseID = createIdForActionCelebs [1];
console.log(cruiseID.id); // 10
        
  22. Sneha

    Hey Richard,
    I am learning Javascript and I really appreciate the efforts u took to explain one of the readers “Roberto” because that really helped me understand clearly.
    Thanks.
    Sneha.

  23. Your blog helps me a lot, and reduce time needed to read all other blogs. I find the information on your blog and the way you are presenting the most informative. Just wanted to say thank you!!!

  24. Foysal Mamun

    really sweet post. Thanks.

  25. Vish

    Hi Richard,
    Sorry for the long post. I wanted to explain my scenario as detailed as possible. I was experimenting with your example to see how it would work if I tweak things a bit. I changed it as follows

    function celebrityIndicator(theCelebrities) {
    var i;
    var uniqueId = 100;
    for (i = 0;i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = function(j) {
    return function() {
    return uniqueId + j;
    }();
    }
    } // did not pass i as a parameter here

    return theCelebrities;
    }

    var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

    var createIdForActionCelebs = celebrityIndicator(actionCelebs);
    var stallone = createIdForActionCelebs[0];
    console.log(stallone.id());

    Instead of passing i as a parameter, I assigned the variable theCelebrities[i]["id"] to the function reference and tried printing the id.

    I got NaN as the output. Why would this happen ?

  26. Sriram

    Hi Richard

    This site is very flexible to learn javascript

    good going.

  27. Ankit Agarwal

    This is really an awesome site to learn javascript.
    I have traversed many other sites for js but i haven’t found such a simple and detailed description.

    Bookmarked this site !!
    Great work.

  28. Alisa

    Hello,
    I’m still struggling with closures but getting um, closer. Where can I find the quiz you mentioned for Feb 7? Muchas gracias, Alisa

    • Alisa, you caught me: I was supposed to post that quiz a while back and I completely forgot. I will think about doing it sometime soon; just for you :)

      Which part of closures are you struggling with? Post your questions here and I will answer them.

  29. Tyler

    Immediately invoking function expressions felt like a greased pig until I read your reply about testing a returned inner function. Once assigned to a variable, logging that variable without parenthesis dumps the function declaration. Logging the variable followed by () invokes the function. And so, assigning a function to a variable and following it with () assigns the function to the variable and runs it.

    Ok, I just re-read what I wrote and I’m confused again… Maybe.

    Curious how a passed parameter doesn’t persist. Perhaps the assignment of the variable using ‘var’ gives the anonymous function a clean slate.

  30. jeff

    Enjoying your site…

    I was playing with a couple of the examples. Now I’m confused about the syntax difference of two of the examples. The 1st example (function showName) returns the closure function as follows:

    return makeFullName (); // the parens are included

    The 3rd example (function celebrityName) returns its closure function WITHOUT the trailing parens as follows:

    return lastName; // no parens

    The 3rd example’s closure function has parameters, the 1st example’s does not, otherwise things seem equal. Dropping parens from the 1st or adding them to the 3rd breaks things.

    What’s going on?

    Thanks,
    Jeff

    • I see that you are paying attention to each line carefully there, Jeff. :)

      In the first example, we are returning the result of executing the makeFullName function. We actually didn’t need the makeFullName function at all; we could have just add the code right inside the showName function (not inside the makeFullName closure). This was example was just for demonstration of what a closure is hence the reason we added the makeFullName inner function.

      But in the second example, we are returning the lastName function BEFORE it is executed, so that we can execute it later. If we return it like this, return lastName(), then it would have executed at that point in the code (where it is defined) and it would not have had access to the outer function’s variables and parameters later because we couldn’t call it later.

      So the reason we return only lastName (without the params) is that we want to execute the function later and so that it can access the outer functions’s variables.

  31. Rakesh Sivan

    I was running between several websites to get a clear picture about closures and also about the java script’s most powerful features in general.Your website has the right stuff with the needed clarity. Thanks :)

  32. nice explanation….I liked very much:)

  33. Petr

    Hi,

    firstly thanks for the articles, they are absolutely amazing. I’m reading through all of them and I will recommend them to other people every chance I get!

    My question – in the last code block example – why does the inner function return another functions? Isn’t that redundant to create a function whose only aim is to return another function? Or am I missing something?

    P.S.: It seems that your comment section has the ability to highlight code, but users don’t use it and I can’t seem to find how to do it either. It’d make the comments section a lot more readable (sexy) though :-)

    Once again, thank you for the great articles!

  34. hausFrauFromHades

    I am really enjoying your articles, particularly this one and the one on callbacks. Thanks for your work.
    JavaScript IS sexy– who knew?

  35. Sarvesh Kesharwani

    You are just awesome.

  36. Shadab

    function lastName (theLastName) {
    return nameIntro + firstName + ” ” + theLastName;
    }
    return lastName;

    in the case above you have written lastname without (),how does js treat this.Is it actually a function call?

    • In JavaScript, functions are object, so you can treat them like an object or a variable. When you return a function without the (), you are returning the function definition. So that you can call the function later. For example:

      function showMe (){
      console.log (“This is Rich”);
      }

      function showRich () {
      return showMe;
      }

      If we run this line:
      showRich ();

      We get this result:
      function showMe() {
      console.log (“This is Rich”);
      }

      Yep, the actual definition of the showMe function.
      But of course it is not very useful just return the showMe function, which is not executing or returning anything itself. The showmen function should execute some action or return something.

  37. Axel

    Hello Richard,

    I think the last example with the nested IIFE´s does not match your intentions (as I suppose them :-).
    The problem is, that all IIFE’s are executed immediately, so that ‘theCelebrities[i]["id"]‘ is a value and not a function anymore. The IIFE’s are equal to assigning the value directly: theCelebrities[i]["id"] = uniqueID + j; (as joncu correctly stated)

    What I suppose you wanted is the following:


    for (i = 0; i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = function (j) {
    return function () {
    return uniqueID + j;
    }
    } (i);
    }

    This will create a new scope for the inner IIFE at "construction time" containing the current value of i.

    Of course the id then must be called (or better – can be calleg) with parnthesises:


    
console.log(stalloneID.id()); // 100

    console.log(cruiseID.id()); // 101

    By the way, this is the best site I saw up to now explaining the (many) JS-obstacles in an easy and understandable way. Great work!

  38. Binh Thanh Nguyen

    Thanks, nice post

  39. Jeremy

    Richard,

    This article is very good up until the end. Your example of IIFE is pretty bad, since the result, as others have pointed out, is that every celebrity is assigned an ID when celebrityIDCreator is called and you might have just as well written:


    theCelebrities[i]["id"] = uniqueID + i;

    Here is a version that uses and IIFE so that theCelebrities.id is still a function but it is not assigned until the id() function is first called. (Then the function is replaced with a new function that always returns the same number.)


    function celebrityIDCreator (theCelebrities) {
    var i;
    var uniqueID = 100;
    for (i = 0; i < theCelebrities.length; i++) {
    (function() {
    var thisCelebrity = theCelebrities[i];
    thisCelebrity["id"] = function () {
    var thisID = uniqueID++;
    thisCelebrity["id"] = function() {
    return thisID;
    }
    return thisID;
    }
    })();
    }
    return theCelebrities;
    }

    var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

    var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

    createIdForActionCelebs[2].id(); // 100
    createIdForActionCelebs[0].id(); // 101
    createIdForActionCelebs[2].id(); // 100

  40. Jack

    Hey man, your site is awesome! I have a question though, for your last example about immediately invoked functions, how come you nested functions instead of a simpler:

    function celebrityIDCreator (celebs) {
    var i;
    var uniqueID = 100;
    for (i = 0; i < celebs.length; i++) {
    celebs[i]["id"] = function() {
    return uniqueID + i;
    } ( ); //INVOKE HERE IMMEDIATE
    }
    return celebs;
    }

    I'm not just providing a simpler solution because that's not the point of this lesson. But the point was a bit lost on me when I had to deal with more confusing IIFEs.

    Could you expound on the point you were making with the last example? Thank you.

  41. shams

    I don’t understand the need of inner function.

    theCelebrities[i]["id"] = function (j) { // the j parametric variable is the i passed in on invocation of this IIFE
    return function () {
    return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array
    } () // BY adding () at the end of this function, we are executing it immediately and returning just the value of uniqueID + j, instead of returning a function.
    } (i); // immediately invoke the function passing the i variable as a parameter
    }

    Cant it be simply ?
    theCelebrities[i]["id"] = function (j) { // the j parametric variable is the i passed in on invocation of this IIFE
    return uniqueID + j;
    } (i); // immediately invoke the function passing the i variable as a parameter
    }

  42. Yui

    Greatest post!! I learn a lot!
    I think this might be a little shorter and it still works:
    http://jsfiddle.net/GGGfW/

  43. Ibrahim Islam

    So, in the celebrity id where the id is being assigned a function that returns modified id example when is the anonymous function is executed actually?

  44. Ibrahim Islam

    In the last example, why are we returning a function and then the modified Id again inside? Why can’t we just return the modified id?

  45. Ibrahim Islam

    Regarding the last code, this is making more sense to me: http://jsfiddle.net/L39jM/

  46. ashish

    You really made Javascript sexy n awsome. !!! Thanks

  47. Kedarnath G

    Awesome Post :

    Excellent Post on Closure. I didn’t think Java script is this much sexy before

    Thanks
    Kedarnath

  48. nice articles and this example is easy to understand, I must say… Thanks

  49. islam al khaldi

    First of all, thank you very much for your this nice and constructive blog.
    Refering to your last example in “Understand JavaScript Closures with Ease”, i think the inner IIFE could be removed, because it works fine without it.
    I tried the example in Firebug and it works and gives the same result.
    function celebrityIDCreator (theCelebrities)
    {
    var i;
    var uniqueID = 100;
    for (i = 0; i < theCelebrities.length; i++)
    {

    theCelebrities[i]["id"] = function (j)
    {
    return uniqueID + j;
    } (i);
    }
    return theCelebrities;
    }
    var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];
    var createIdForActionCelebs = celebrityIDCreator (actionCelebs);
    var stalloneID = createIdForActionCelebs [0];
    console.log(stalloneID.id); // 100
    var cruiseID = createIdForActionCelebs [1];
console.log(cruiseID.id); // 101
    Thanks :)

  50. bhanu

    Thank you
    i had got a clear picture on closures

  51. A great explanation

  52. hello robert, i think there is typo here
    // It will return the current value of celebrityID, even after the changeTheID function changes it

    changeTheID = setID

  53. is there a problem if the function name is the same as a variable name declared within it? (i think you mentioned in your hoisting/scope article that this is not good practice no?) in this case celebrityID is used as both a function name and variable name. how does the engine treat them? is there any hoisting going on here?

  54. in point number 2 of rules and side effects, you said the celebrityID function demonstrates the use of private variables. can you please explain what private variables are and how passing by reference enables the use of it? while on the topic, whats the diff between a private and a local variable?

  55. hi robert,
    on the very last example, wouldn’t it have been cleaner to do away with closures altogether, instead of having to trouble with IIFE?

    for (i = 0; i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = uniqueID + i;
    }

    BTW, the quiz you mentioned posting on feb 7, how can i access that?

  56. sorry richard, been calling your name wrong LOL.

  57. hi robert, it seems in the IIFE implementation, id is now no longer a function, but rather just a number.

    >createIDForActionCelebs[0].id()
    TypeError: number is not a function

    >createIDForActionCelebs[0].id
    =>100

    how can we modify code to make it return function, just like before using IIFE?

    • Cenob

      The short answer:
      remove the “()” that comes just before the comment starting in “// BY adding () at the end of this…”

      By the way, the solution above can be deduced by reading the entirety of that comment, which is:
      // BY adding () at the end of this function, we are executing it immediately and returning just the value of uniqueID + j, instead of returning a function.
      Note that if you copy-pasted the IIFE code and you make the change noted above, you’ll also need to change the console.log lines to reference the ‘id’ attribute as a function “.id()” instead of as a value “.id”.

      But wait, why was this question even asked (and the ones by soncu, tanyaka, and Pearce)?
      Given that the article was written to explain closures, it doesn’t make sense to return values instead of functions in the IIFE example code.

      I’m just getting started on Javascript, so please check my facts here but I don’t think the code using IIFEs is a closure since no references to celebrityIDCreator’s local variables persist after the function returns, and as such there’s no need for IIFEs.

      I’m pretty sure the IIFE example was originally written to return functions, but that it was changed in conjunction with the note on May 27th, 2013 where Richard wrote “I just updated the code in the article to store numbers in the returned array, instead of functions.”

      **Please change it back.**

      The change reduced the celebrityIDCreator function from a closure to a plain function, and as such removed the need for IIFEs, and also left the “closures gone awry” problem unsolved.

      Thank you for writing this up Richard, it was very helpful and I’m sure it will continue to help people after me, which is why I bothered with this big post.

  58. wdc

    Call me old school (go ahead, I don’t mind, I’ve been programming since 1974 :), but I honestly don’t see why closure is a good thing. IMO it only allows for obscure, unreliable code. Even in what the first couple of side effect examples, #1 and #2, shows us, you’re telling me that (in #1) the value of ‘Michael’ hangs around in memory, from a previous call to the celebrityName function, so that the subsequent call to the lastName function via the mjName returned function utilizes ‘Michael’ at that time? Why is something like this a good thing? Doesn’t example #2 show why this isn’t a good thing? I would rather have/write software that doesn’t allow stuff like this to happen. Are you telling me that there is a case in which closure HAS to be used, because there is no way to provide a certain functionality by writing functions (most likely by not nesting functions) that does NOT utilize closure in that kind of way? If it IS true that I can write code that provides a certain functionality by not nesting functions and not utilizing closure, in every case where I might see closure being utilized, then I would contend that code that performs that functionality without closure will always be more understandable and reliable than code that utilizes closure, even if the code not using closure takes more lines of code and isn’t regarded as being as “cool” or concise. I would gladly trade more lines of code for better readability/understandability and better reliability/maintainability. If you could provide an example of code that shows the utilization of closure in a way in which the same functionality of that code CANNOT be performed with code NOT utilizing closure, then maybe I would be more open to the technique. It seems to me that sometimes languages working in such a way as this is more because of accident than by original intentional design, and then people start using it just because they can write supposedly “elegant” code that no one else can figure out how it works (at least not without a lot of effort).

    • jwalker

      Awesome man! Exactly what I was thinking. Writing code like this is just confusing and totally unnecessary.

  59. I have written the last code in a different way. it is showing same output. but is it the correct way to do?

    function celebrityIDCreator (theCelebrities) {
    var i;
    var uniqueID = 100;
    for (i = 0; i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = function () {
    return uniqueID + i;
    }();
    }

    return theCelebrities;
    }

    var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

    var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

    var stalloneID = createIdForActionCelebs[0];
    console.log(stalloneID);

  60. John

    Hi Richard,

    Thanks for writing such a helpful JS blog! I’m having trouble generally understanding when closures should be used. Why would we use a closure to create IDs in the celebrity example? Couldn’t we just do the following with the same effect?


    function celebrityIDCreator (theCelebrities) {
    var i;
    var uniqueID = 100;
    for (i = 0; i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = uniqueID + i;
    }
    return theCelebrities;
    }

    • Hi John,

      Richard explained why that wouldn’t work in the post here, which I have unashamedly copied and pasted as I couldn’t have explained it better :p

      “In the preceding example, by the time the anonymous functions are called, the value of i is 3 (the length of the array and then it increments). The number 3 was added to the uniqueID to create 103 for ALL the celebritiesID. So every position in the returned array get id = 103, instead of the intended 100, 101, 102.

      The reason this happened was because, as we have discussed in the previous example, the closure (the anonymous function in this example) has access to the outer function’s variables by reference, not by value. So just as the previous example showed that we can access the updated variable with the closure, this example similarly accessed the i variable when it was changed, since the outer function runs the entire for loop and returns the last value of i, which is 103.”

      TL;DR: Because closures access the outer function’s variables by reference, therefore, it will not work the way you anticipate it to.

      To Richard:

      I have a question for the revised edition, couldn’t I have done it like so?

      function celebrityIDCreator (theCelebrities) {
      var i;
      var uniqueID = 2000;
      for (i = 0; i < theCelebrities.length; i++) {
      theCelebrities[i]["id"] = function (j) { // the j parametric variable is the i passed in on invocation of this IIFE
      return uniqueID + j;
      } (i); // execute it now and pass in i
      }

      return theCelebrities;
      }

      var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

      var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

      var stalloneID = createIdForActionCelebs [0];
      
console.log(stalloneID.id); // 100

      var cruiseID = createIdForActionCelebs [1];
console.log(cruiseID.id); // 101

      Please advise thanks!

      • Deepak

        Yes , I have also the same doubt. Why to write another IIFE inside an IIFE , as inside the first IIFE we can directly return the value.

  61. Kaustubh

    Thanks Richard for this useful blog.
    function closure is the true heart of javascript and you helped understanding it better

  62. wdc

    I’m still trying to understand why closure is a “good thing”.

    Let me take another short stab at justifying it as a language feature and coding technique to use.

    In one of your comment responses, you say:

    ‘So the reason we return only lastName (without the params) is that we want to execute the function later and so that it can access the outer functions’s variables.’

    That statement (particularly the word “later”) made me think of an aspect of closure that I can actually accept as being useful. Could one say that the real, underlying usefulness of javascript closure (at least one useful thing, anyway) is that it allows for a kind of data persistence without having to use an actual datastore? IOW, that it is a kind of “in-memory” datastore, with respect to the outer function’s variables and parameter values?

    Basically (stated another way), that closure allows “setting up” a function (the inner function) for execution sometime LATER in time, knowing that the values of the outer function’s variables and parameter values will still be there (have been “stored” in memory for use later)? WITHOUT having to store those values in a file on disk, or in an actual database, etc.

    This is what I have found lacking in every discussion/explanation of javascript closure – underlying, conceptual REASONS why closure is valuable, not just how the code works in a mechanical sense (and with “mickey mouse” examples that don’t even seem useful in a real-world sense on top of it, which compounds the problem of old-timers like me being able to accept it as a good thing (if you read my previous post)).

    ASSUMING that what I am observing in this post is correct – that at least one of the main, beneficial, underlying reasons for closure is that it allows “setting up” a function for later use, and “remembering”, or persisting some data values in memory for use at that later time, without having to use a formal datastore… Can you verify this particular take on it, or am I off-base about it?

    If so, then I can grudgingly see how javascript closures might be useful for that particular scenario :)

    BECAUSE (to expand on the conceptual reasoning) from a software architecture / OOP viewpoint, it allows a function (the inner function) to be polymorphic in the sense that it will have different behavior when it is invoked, based on the values that were passed into the outer function at some previous time.

    THAT I can understand and see as being useful.

  63. Thanks for corunibtting. It’s helped me understand the issues.

  64. tank u so much for your great post.i was studying about Java 8 new features such as anonymous class and thinking about applying it as closure. and comparing with javascript closure. javascript is much sexier than any language. I think many of new programming concept such as generic in other programming languages can be implemented easily with javascript clousures. am i right?

Trackbacks for this post

  1. 16 JavaScript Concepts You Must Know Well | JavaScript is Sexy
  2. JavaScript Variable Scope and Hoisting Explained | JavaScript is Sexy
  3. Learn Node.js Completely and with Confidence | JavaScript is Sexy
  4. Learn Backbone.js Completely | JavaScript is Sexy
  5. 12 Simple (Yet Powerful) JavaScript Tips | JavaScript is Sexy
  6. Learn Everything About JavaScript Callback Functions | JavaScript is Sexy
  7. Closures. Definición y aspectos básicos. ← Javascript docs
  8. JavaScript Closures | Geek Girl Arises
  9. Simple Yet Powerful JavaScript Tips | Hackya.com
  10. Apply, Call, and Bind Methods are Essential for JavaScript Professionals | JavaScript is Sexy
  11. Module Pattern in JavaScript | A Developer's Insight
  12. Mateo Clarke | Week 5 Review
  13. Node.js 내가 쓰기로 선택한 이유. | Vine Brancho
  14. Javascript Interview Questions | KRIYANCE
  15. JS and JQuery | Pearltrees
  16. Linux Commands and important Links for Reference | sureshat25
  17. JavaScript closures work | Coding and Programing
  18. A little bit about JavaScript closures | Leaves of Code
  19. NSS Day 12 – Holla’ back | Hyperbolic Time Chamber

Leave a Comment