Understand JavaScript Closures With Ease

»feb. 2 2 Years Ago 143

Closures allow JavaScript programmers to write better code. Creative, expressive, and concise. We frequently use closures in JavaScript, and, no matter your JavaScript experience, you will undoubtedly encounter them time and again. Sure, closures might appear complex and beyond your scope, but after you read this article, closures will be much more easily understood and thus more appealing for your everyday JavaScript programming tasks.

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.

  • Receive Updates

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

Our Course Website Is Now Live!!

New UPDATE on March 29

Two Quick Notes:
  1. Go now and check out the course website at the link below. (You cannot enroll yet, but you will be able to next week.)
  2. If you want to be one of the first enrollees, Email Us at enrollment@modern-developer.com, after you checkout the course website at the link below.
https://learn.modern-developer.com

143 Comments

  1. Nimesh

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

    • Richard Bovell (Author)

      Thanks much, Nimesh. I am happy to hear the website is helpful and…sexy, too. :)

      • vedran

        Very good site !!!!

      • DeVontae Moore

        theCelebrities[i][“id”] = function (j) {

        Im not familiar with the above syntax. Could you please explain?

        • MS

          This statement assigns a new value to a variable inside an array of objects.

          Recall that theCelebrities now has the value of [{name:”Stallone”, id:0}, {name:”Cruise”, id:0}, {name:”Willis”, id:0}]
          The first set of square brackets, theCelebrities[i], calls an object by its array position. If i = 0 then theCelebreties[i] is equal to the first object in the array, in this case, {name:”Stallone”, id:0}.
          The second set of brackets, [“id”], call that object’s property by its name “id” .
          The rest of the statement “= function(j){….}(i)” simply reassigns the value of the property “id” from “0” to the return of the function.
          On the macro level {name:”Stallone”, id:0} becomes {name:”Stallone”, id:100}.

          This type of index referencing works with any type of nested array:
          if a = [4, [apple, 7, triangle, [88, 69], 6, 6], tomorrow] then:
          a[1][3][0] is equal to 88; and
          a[2] is equal to tomorrow;
          Hope that helps ;)

  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?

    • Richard Bovell (Author)

      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. ;)

        • Richard Bovell (Author)

          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.

        • Bryson

          Yep, agreed. I’ve been trying to understand closures on and off for two years… This might have just finally solved it for me!

      • 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?

    • Richard Bovell (Author)

      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 :) :)

    • Richard Bovell (Author)

      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.

    • Hadar

      Exactly what I thought!
      Too bad you didn’t get an answer for that until today.. this could be *very* helpful.

  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

    • Richard Bovell (Author)

      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.

    • Richard Bovell (Author)

      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!

    • Richard Bovell (Author)

      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

      • DeVontae Moore

        It could you point out your fact about the code returning a function and calling that function later.
        I saw it clearly in your IIFE tutorial:
        showName = function (name) {console.log(name || “No Name”)}) (); // No Name​

        showName (“Rich”); // Rich​
        showName (); // No Name

        but dont see those same principles here.Thank you for your time

  16. sameer

    Thanks for the sexy website

    • Richard Bovell (Author)

      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

    • Richard Bovell (Author)

      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

  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.

      • Bart Kleijngeld

        I had the exact same question as Jeff, and would like to make sure I understand your explanation. Can I summarize it as follows?

        In the first example a closure is defined in the most basic way, the purpose to show what a closure is basically, _but_ it is a useless example and in practice one will always encounter the returning of closures for them to be useful?

        Thanks for the great article!

  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. 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 :)

  49. bhanu

    Thank you
    i had got a clear picture on closures

  50. 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.

  51. 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;
    }

  52. Kaustubh

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

  53. 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.

  54. bayloox

    Thanks very much for the post.

    The “sexy” for JS is catching on man. If it becomes global all the credit will be yours!

  55. Kevin

    Hey Richard,

    First of all I would like to thank you for this website because it has really aroused my interest in JavaScript so much so that I really wanna dive more into it.

    Now coming to the doubt that I had; in the “Closures Rules and Side Effects” section no. 2 you made a statement that said,

    “
Closures get more interesting when the value of the outer function’s variable changes before the closure is called.”

    My only doubt in the above scenario is that the example is simple to understand but can you please elaborate more on this topic since the statement is not clear enough from the example that you have given.

  56. Hey there, thank you once again, you have been a great resource. I have been finding some great resources here.
    Well article.. i just love Javascript!

  57. maaz

    aslamualykum
    i am proud of you
    because you solved lot of my problems.
    thank you so much sir .

  58. DeVontae Moore

    Im not familiar with the following syntax and its purpose:
    theCelebrities[i][“id”]

  59. ARSHAD

    WOW!!! SUCH A NICE WAY TO EXPLAIN THE CORE CONCEPTS.. JAVASCRIPT IS REALLY GETTING SEXIER FOR ME NOW… :)

  60. It’s a great post. But there’s not so much ease. The rule 1 example never could make it into my brain, so I refactored it to make as clear as possible, with descriptive variable names and output harness included. Then the d-oh lamp lit up.

    function celebrityNameMunger(firstName) {
    var nameIntro = “This celebrity is “;
    // this inner function has access to the outer function’s variables, including
    // the parameter
    function lastNameAppender(theLastName) {
    return nameIntro + firstName + ” ” + theLastName;
    }
    return lastNameAppender;
    }

    console.log (” celebrityNameMunger is global: ” + celebrityNameMunger );
    console.log (” …and now the closure lastNameAppender gets assigned to mjNameBuilder…” );
    var mjNameBuilder = celebrityNameMunger(“Michael”);

    console.log (” >>>>>>>>>mjNameBuilder >>>>>>>: ” + mjNameBuilder );
    // At this juncture, the celebrityNameMunger outer function has returned.?
    // The closure (lastNameAppender) is called here after the outer function has returned above
    // Yet, the closure still has access to the outer function’s variables and parameters

    console.log (“mjNameBuilder(‘Jackson’): ” + mjNameBuilder(“Jackson”)); // This celebrity is Michael Jackson

    We loggin’, bro

  61. Sakthivel

    Hi,

    Excellent Stuff!! Appreciate your work. Nice to learn.

  62. Closure is one of the most headache issue in Javascript and I usually find hard to explain that to my developers. This post is very helpful and easy to understand. It helps me a lot for training devs of my team. Thanks for sharing.

  63. Tarak

    Really sexy stuff i found……

  64. Mark

    In your last example, doesn’t

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

    create the same effect with one less level of convolution? although maybe I'm just missing the point you were trying to make.

  65. Samir

    Dude you are awesome and your website is sexy. Keep doing sexy work :)

  66. 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.

  67. 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.

  68. 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.

  69. Nick

    I’ve done the same thing.

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. How to: How do JavaScript closures work? | SevenNet
  12. How to: How do JavaScript closures work? | Technical information for you
  13. JavaScript Closures | Pradeep Reddy Kamatham
  14. 「译」不侧漏精通 Node.js – 千月殿 -
  15. Solution: How do JavaScript closures work? #dev #it #computers | Good Answer
  16. Як розмістити на сайті мапу від Google | Нотатки PHP розробника
  17. PHP یا Node.js ؟ مساله این است!
  18. AngularJS Pattern: Handling Data From AJAX USING Javascript Objects: Part II | MO MOADELI

Leave a Reply

Current ye@r *