Understand JavaScript Closures With Ease

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

Email Address :

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:

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:

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:

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:

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:

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 😉

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:

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

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.

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.

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.

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.

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:

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.

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:

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

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

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

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.

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

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.

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.

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?

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

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

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.

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)

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

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
}

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++)
{

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

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?

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.

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.

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.

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

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.

Thanks a lot for this post. It’s great, I’ve learned a lot from your site. FYI, I’m new to Javascript.

But I was wondering if the following paragraph could be made a little clearer, (right after the “Closures gone Awry” section).

“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.”

changed to…

“In the preceding example, AFTER THE LAST CALL OF THE ANONYMOUS FUNCTION (singular) IN THE FOR LOOP, the value of i is 3 (the length of the array and then it increments). THE UPDATED VALUE OF i=3 IS THEN ALSO APPLIED TO THE PREVIOUS CALLS OF THIS ANONYMOUS FUNCTION, CREATING 103 FOR ALL celebritiesID. So every position in the returned array get id = 103, instead of the intended 100, 101, 102.”

I read this section like 4-5 times and was still confused, but I think I finally understand.

I could be wrong (as I am a total noob at js), but I think it’s because the
anonymous functions are being called _after_ the outer function has gone out of
scope, at which time i has reached the value 3 and terminated the for loop.
Now, because it was a reference to an anonymous function being stored in the
array, the function hasn’t been called yet, but when it is, it is referencing
the value of i at the time of call, which will yeild 3, the value that
terminated the loop; I hope this helps (and I certianly hope it’s correct lest
I give bad information).

Hi Richard,
It is the best explanation on closures. The difficulty in understaning is due to our habitual thinking.
1. In Closures gone awry section, in each iteration of the loop, what is assigned is NOT a value BUT a function. The same (anonymous) function is assigned(saved) but NOT executed. When we called the saved function later, the function has latest values.
2. The debate on whether closures are good or bad is another story.
Thanks a lot for the post.

Example for closure holding reference is not correct. Because Number is immutable data type. If you change the Number then its reference will also be changed.
Reason because it has 3 is, thats what the value of its outer function’s variable when the closure is called.
Closure is simply a function defined inside an object anonymously. We all know that Function is an Object, closure will have access to the variables of the object(ie., function) it defined.

I’m not sure if you’re aware, but Hack Reactor is referencing this article for potential students who are trying to learn JavaScript, so I figured I would make a few suggestions…

First, in your second point, both the name of your outer function AND the variable inside it is the same (i.e. CelebrityID). This is confusing, and if I’m not mistaken, it produces an error. Additionally, in that same section, you make reference to a “changeTheID function” (which doesn’t exist). I believe you meant to reference the “setID” function.

And finally, regarding section three, I don’t quite understand why an IIFE inside of an IIFE is being used here (along with another parameter). Wouldn’t the following code suffice?

Thank you for such a great explanation. I had seen some articles explaining closures but I wasn’t able to wrap my head around it until I read this comment. Perhaps you might consider adding it to the blogpost (maybe as a side note or something). It truly is a great explanation Thanks again!

Thank you so much for this reply! I have been hung up on this exact example since I read it in eloquent JS and the explanation is SIMPLE, I just never got that the outer function returned the inner one. Thank you sexyJS.

The fact that a contained function may access a variable in the closure, and that variable may change before the contained function executes is not a bug as you keep saying. It is intended functionality. You just have to know how closures work, which the rest of your article demonstrates very well.

please help solve a tabular array to change the cars in sequence ona platform ‘demo’ when this displays make the image hover on the other cells.thanx var cars=[]; cars[0]= ida; cars up to INDEX[11] and their ids. when i use a closer it only shows the last image bt dont loop

This is quite simply one of the finest JavaScript tutorials out there. In fact, I was asked about JavaScript closures in a phone interview today. I wish I had read this first. Doh! Can I ask what a parametric variable is?

The result was as expected. The javascript engine could make copies of the functions and objects to maintain the scope. I’m wondering if persistent scope is implemented by referencing the objects or if copies are made containing only properties that have been used in declarations yet to be executed; and if it makes a difference to how callbacks are handled. It seems that it probably doesn’t matter; the scope remains as though the outer function is still running. It starts to get confusing in things like angular.js

Thanks for the post. I am not clear with this line
“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.”

Let’s consider their practical implications. A closure lets you associate some data (the environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object’s properties) with one or more methods.

Consequently, you can use a closure anywhere that you might normally use an object with only a single method.

Situations where you might want to do this are particularly common on the web. Much of the code we write in web JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.

Here’s a practical example: suppose we wish to add some buttons to a page that adjust the text size. One way of doing this is to specify the font-size of the body element in pixels, then set the size of the other elements on the page (such as headers) using the relative em unit:
body {
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
}

h1 {
font-size: 1.5em;
}

h2 {
font-size: 1.2em;
}123456789101112

Our interactive text size buttons can change the font-size property of the body element, and the adjustments will be picked up by other elements on the page thanks to the relative units.

size12, size14, and size16 are now functions which will resize the body text to 12, 14, and 16 pixels, respectively. We can attach them to buttons (in this case links) as follows:
document.getElementById(‘size-12′).onclick = size12;
document.getElementById(‘size-14′).onclick = size14;
document.getElementById(‘size-16′).onclick = size16;123121416123

Closures have access to the outer function’s variable even after the outer function returns….
I don’t find this point correct. The lastname function is called before the the outer function returns.
I think the sequence is:
celebrityName function called
lastName function called
lastName function returns
celebrityName function returns.. I am applying the concepts of assembly language programming.

The best thing I learned today. I have seen this in our project and thought why they have written like this without knowing that they were Closures. Really felt like I achieved something when I learned and written some examples based on Closures. 😛
Great work. Applause !!!

Is the inner function body required to be nested inside the outer function or the reference would also work?

callService(abc,pqr,239,function(data){
anotherFunction(data,345,998); //data gets available to the function.
anotherFunction(345,998); //data is un available to the function.
});
It would have worked if the anotherFunction body was nested inside instead of the reference?
Please clarify.

I console.logged mjName and just got the function definition of lastName, why is this?

Also after mjName returns after passing “Michael”, and we call it again with “Jackson”, how does the function know which parameter to pass these arguments to? How does it “know” whether to pass each argument to firstName or theLastName? For example, why doesn’t it overwrite “Michael” with “Jackson” or mixup firstname and theLastName?

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.

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.