Explaining JavaScript scope and closures

I thought I’d try to explain something which many people struggle with: JavaScript scope and closures.

Background

There are a number of articles and blog posts out there trying to explain scope and closures, but overall I’d say that a majority of them aren’t crystal-clear. Besides, a number of them take for granted that everyone has developed in about 15 other languages before, while my experience is that a lot of people writing JavaScript come from a HTML and CSS background, instead of C and Java.

Therefore, my humble goal with this article is for everyone to finally grasp what scope and closures are, how they works, and especially how you can benefit from them. You do need to understand the basic concepts of variables and functions before reading this.

Scope

Scope refers to where variables and functions are accessible, and in what context it is being executed. Basically, a variable or function can be defined in a global or local scope. Variables have so-called function scope, and functions have the same scope as variables.

Global scope

When something is global means that it is accessible from anywhere in your code. Take this for example:

If you take a look at the code above, the variable saying is only available within the talkDirty function. Outside of it it isn’t defined at all. Note of caution: if you were to declare saying without the var keyword preceding it, it would automatically become a global variable.

What this also means is that if you have nested functions, the inner function will have access to the containing functions variables and functions:

As you just saw, the inner function capitalizeName didn’t need any parameter sent in, but had complete access to the parameter firstName in the outer saveName function. For clarity, let’s take another example:

As you just saw, both inner functions have access to the siblings array in the containing function, and each inner function have access to the other inner functions on the same level (in this case, joinSiblingNames can access siblingCount). However, the variable siblingsLength in the siblingCount is only available within that function, i.e. that scope.

Closures

Now when you hopefully have gotten a better grasp of what scope is, let’s add closures to the mix. Closures are expressions, usually functions, which can work with variables set within a certain context. Or, to try and make it easier, inner functions referring to local variables of its outer function create closures. For instance:

That function closes the context and remembers what the parameter x was at exactly that time (i.e. 5 in the code above)

When the result of calling the add function is assigned to the variable add5, it will always know what x was when it was initially created.

The add5 variable above refers to a function which will always add the value 5 to what is being sent in.

That means when add5 is called with a value of 3, it will add 5 together with 3, and return 8.

So, in the world of JavaScript, the add5 function actually looks like this in reality:

function add5 (y) {
return 5 + y;
}

The infamous loop problem

How many times have you created some sort of loop where you wanted to assign the value of i in some way, e.g. to an element, and found out it just returned the last value i had?

Incorrect reference

Let’s take a look at this faulty code, which creates 5 a elements, adds the value of i as a text to each element and an onclick which is expected to alert the value of i for that link, i.e. the same value as in the a element’s text. It then appends them to your document body:

Each a element gets the correct text, i.e. “Link 0”, “Link 1” and so on. But whichever link you click, it alerts the number “5”. Oh my God, why? The reason for this is that the variable i get its value increased with 1 for each iteration of the loop, and since the onclick event isn’t being executed, just applied to the a element, it adds up.

Therefore, the loop continues until i is 5, which is the last value of i before the function addLinks exits. Then, whenever the onclick event is actually being triggered, it takes the last value of i.

Working reference

What you want to do instead is create a closure, so that when you apply the value of i to the onclick event of the a element, it gets the exact value of i at just that moment in time. Like this:

With this code, if you click the first a element it will alert “0”, the second “1” etc; just what you probably expected with the first code I showed you to do. The solution here is that the inner function of what’s applied to the onclick event create a closure where it references the parameter num, i.e. what the i variable is at just that time.

That function then closes with that value safely tucked away, and can then return its corresponding number when the onclick event is being called.

Self-invoking functions

Self-invoking functions are functions who execute immediately, and create their own closure. Take a look at this:

Ok, so the dog variable was only available within that context. Big deal, man, hidden dogs… But, my friends, this is where it becomes really interesting! It solved our problem with the loop above, and it is also the base for the Yahoo JavaScript Module Pattern.

Yahoo JavaScript Module Pattern

The gist of the pattern is that it uses a self-invoking function to create a closure, hence making it possible to have private and public properties and methods. A simple example:

The beauty of this is that you now can decide on your own what will be publicly visible for your object (and can be overwritten), and what is private and no one can access nor alter. The variable name above is hidden outside the context of the function, but accessible from the returned getName respectively setName functions, since they create closures where they have a reference to the name variable.

Conclusion

My sincere hope is that after reading this, novice or experienced programmer, you have gotten a clear view of how scope and closures actually work in JavaScript. Questions and feedback are very welcome, and if any input is deemed important enough, I will update this article with it.

I must say I already was familiar with most concepts you describe, but it's good to have them explained again all in one place for quick reference. Especially the infamous loop problem sometimes still bites me in the ass 😀

The key is that the function is self-invoked, i.e. gets executed right away, and sends in the value <code>i</code> to be the value of <code>num</code>.

If you examine that part of the code more closely:

<code>link.onclick = function (num) {

return function () {

alert(num);

};

}(i);</code>

you can see that it is not just assigned, but actually gets called immediately by having two parentheses at the end, with <code>i</code> in them.

And since inner functions will always have access to their outer/containing functions' variables (i.e. a closure is created), it will always know that <code>num</code> is the value of <code>i</code> when it was initially called.

Thanks for a great article Robert. I also missed the (i) at the end of the onclick function and was wondering how num = i —makes sense now that you pointed it out, though.

I also appreciate you using an example that most of us have problem run into (where i was not what we expected, but instead was the last known value). I think that makes a big difference in helping folks to understand.

[…] Explaining JavaScript scope and closures JavaScript handles scope somewhat differently from other common programming and scripting languages, and it also has an interesting capability for creating and using closures. Robert Nyman explains the concepts clearly. […]

Great article! This would have saved my ass on a project just a couple of months ago. The closure bit has caused numerous problems for me and most of the solutions I found on the internet were either half-assed or explained nothing, which left me with a viable solution but defenseless for the next time I ran into that problem. Thanks!

Ironically, there are many C or Java programmers that are well educated but use poor form. My C++ professor in college taught us all kinds of bad practices, like using global variables and <code>system("PAUSE");</code> instead of <code>cin.ignore();</code> or some other less intrusive object. JavaScript is so much easier to work with if you coming from a strong C++ background where you are mindful of C++'s built-in precautions against scope problems that are essential to OOP, because JavaScript lacks any such thing, being a loosely typed language. It's easy to fall into sinkholes when beginning with JavaScript.

[…] reading this article, I strongly recommend reading JavaScript inheritance – how and why and Explaining JavaScript scope and closures first, since many phenomenon below will have their explanation […]

As you can see, it's still a very valuable read even after some months. And being such as it is, I believe it will stay for a long time, for people looking into Javascript a bit deeper than just the newbie stuff…

Your explanation of closures finally cleared the concept for me – I read a couple of them before, but still wasn't entirely clear about what's going on – now I can use them wisely 🙂

I'm a newbie coming from a HTML/CCS background and this was the best and clearest explanation of these topics that I've found on the web

In the "Infamous Loop" example I have a question:

'the Incorrect reference states "the onclick event is not being executed", which I understand, whilst in the Working reference the onclick event appears to be at least evaluated, because the "value is tucked away" '

In regards to the loop, it's hard to catch the first time, but in the working example the <code>onclick</code> is assigned a function that is run immediately. If you check, you can see the two parentheses after the function that sends in the value of i, just as it is during that iteration in the loop.

That means that the current value of is, indeed tucked away, and later referenced when the element is being clicked.

Many thanks for such a succinct article! I'm rather new to all this and it took a bit of time to get my head around self-invoking functions.

If anyone is still struggling, correct me if I'm wrong but for your 'infamous loop' problem, if for the sake of argument you call the addLinks function declaration (all the loop and stuff) 'splurge', then am I right in thinking that the function call is done immediately by the declaration 'splurge'(i); ?

About <code>addLinks</code>: it is rather that within each iteration of the loop, an inner function is called immediately to get a reference to the value of <code>i</code> at that specific time, and then assign that value to the <code>onclick</code> event of the link.

> Can you have a self-invoking function without a closure?

> If so, would there be any benefit to doing this?

Well, a self-invoking rather creates a closure immediately. Then it is up to you if you want to take advantage of what's offered with that or not.

> If you use closures, what about memory leeks?

I believe older versions of Internet Explorer had some memory issues with this, but that they should be sorted out by long. Or at least so I hope! 🙂

Nice! However, you are overwriting something on a global object, so it will not allow you to have multiple <code>window.onload</code> – just thought I'd mention that. 🙂

And sure, it's a closure. Whatever you put in there, i.e. that doesn't explicitly overwrite something that exists outside of it, is only valid and reachable from within that code. If you want to return something to the outside, though, you can use a <code>return</code> statement in that anonymous function, which will be returned globally.

However, really, don't worry about this. All major JavaScript libraries, such as jQuery and others, completely rely on closures as well. So, closures is a de-facto approach to efficient JavaScript programming.

Thanks for all the tips and and your full explanation about closures. I really get it now! I'll definitely check out the script fixes. Closures certaiinly look the way to go, especially as you explained above they're very handy for OOP and encapsulation.

On an aside about onload, good job you pointed that out. I must admit I tend just to pile everything into init and have one onload, not the best way if you have a team working on a project I suppose, but never have any problem with it. I suppose one day I'll have to catch up with the modern approach… 😉

Nice to see that you are still responding after 2 years. I just wanted to say thanks. I have been looking through the voodoo that is jQuery and this article really helped me understand scope and closures. Maybe you can help with this also…

<code>

;(function( scope ){

var Benchmark = scope.Benchmark = function( tests ){

// store the argument { name: test }

this.tests = tests;

</code>

The leading ; is evading my understanding. Also, I do not really understand the second line at all.

^^ Sorry, I know the article is about closures, but if I know anything about beginning JS developers, if they see your solution to the problem, they will always use that solution to the problem – even if the article is context of one issue: closures & scope. Its certainly what i did many, many years ago, but no longer do. Meaning, it may not be the best solution to the problem – but only 1 in context of the article.

Also, be careful if you reference a DOM element in the closure and don’t nullify and then delete the reference. Because of IE garbage collection, you can create a circular reference and pull your hair out trying to find out why there is a memory leak. In an iteration, if you have a dom element that you want to reference later in the extended scope of a closure, be sure test for the object, then at the end of the iteration, nullify and then delete the local reference.

Better yet, instead of adding an anonymous function, add a real function as an event instead, and you won’t have to worry about circular references being created as you add events to DOM elements or even better: add a closure to protect against a circular reference, inside the closure… i know its odd but thats IE.

First of all, I think it’s vital for developers to understand core JavaScript and not just depend on JavaScript libraries. When they understand the workings of JavaScript, absolutely, but some basic understanding is really desired. Therefore, it is anomy about core JavaScript here.

And sure, there coupled be examples where you call an another, function-external function as well or declare the function in the loop initiation.

Regarding circular references, if I’m not mistaken, is that not something that only applies to IE6 and has been fixed since?

Closures are fine, I learned them from Danny Goodman’s books, but they’re difficult like certain Mathematics concepts. For instance, learning about logarithms, or sorting algorithms is easy, but you can find yourself in an unusual situation where the algorithms you need to use are different from what you may have practiced.

Do you know of any resources more comprehensively studying the concept of closures in JavaScript?

You will get the same output, yes. The difference is that you need to instantiate and can’t use the power of prototypes, whereas the Yahoo Module Pattern could be completely anonymous and needs no instantiation (but rather just execution by the parentheses at the end).

[…] from it with only one parameter and the other 2 set to specific values you can do this with closures. There are probably other tricks you can do, but I used this one to help troubleshoot one of my […]

The only thing I don’t understand here is why you name Modular Pattern as Yahoo JavaScript Module Pattern?? It is not like they created something original right? It is used by many developers and hasn’t been invented by Yahoo.

Just want to thanks for your excellent explain. Really helps me a lot. I’ve translate your work to Traditional Chinese(which use in Taiwan and Hong Kong), mark with your name and have a link to this post. Many tanks again!

[…] will have access to the outer scope even after the outer function is executed. This is basically a closure — an expression which can work with variables set within a specific context. For example: […]

So, the explanation for “The infamous loop problem” seemed to be missing the common programming language I would expect. For a javascript function, the parameters are passed to the function by value, not be reference. In other words, the function gets a “copy” not a “pointer” to the original data.

So, if you don’t do the wrapper function, you get a reference to the exact variable defined in the loop, hence it’s the last value it was assigned.

Might be useful to update the wording, so it’s not quite so confusing as to “why” javascript works that way.

Hi Robert,
Really a very good article.
I read same examples before in other articles but with your article i understood them.
It helped me a lot to understand closures.
You explained it in simple words.
Thanx a lot…:)

The result of calling the add function with a value is then saved as a new function that you can call. That means that any value you send in to add5 (e.g. 3) that will be the y value in the function. It’s basically like the x value is hard-coded from before, and the sent in value is the dynamic one, the y one.

Just wanted to say thank you! You really saved my day. I was looking at the opposite problem today, having created a number of closures that keep the context of the creation time, while I needed them all to use the same reference to the latest state instead. I suspected it had something to do with closure scope and context and your post was the first hit on Google when I started researching.

I have a PHP back-end programming background and I’ve used JavaScript for minor things on the front-end, but now I’m learning how to program in it. I’m reading eloquent javascript and couldn’t grasp closures, so in doing further research before continuing with my reading I came across your page. Your explanation is excellent. Thanks Robert!

I do have a question though. Turns out that I’ve been looking at closures lately because someone asked me about broken code that doesn’t uses closures (besides the infamous loop example, which can also be considered using a list), and I’m having a lot of troubles coming up with something. I’ve been looking around for bad closures in JS but with no luck. Seems that everyone kinds of forget about the problem once it gets solved, I know I have 😛

Do you know any other snippets that shows issues because closures are not created?