Closures in JavaScript by kirupa (https://www.kirupa.com/me/index.htm) | filed under JavaScript 101 (https://www.kirupa.com/javascript/learn_javascript.htm) By now, you probably know all about functions (https://www.kirupa.com/html5/functions_in_javascript.htm) and all the fun functiony things that they do. An important part of working with functions, with JavaScript, and (possibly) life in general is understanding the topic known as closures. Closures touch upon a gray area where functions and variable scope (https://www.kirupa.com/html5/variable_scope_js.htm) intersect: [Image: ] (https://www.kirupa.com/html5/images/gray_area_200.png) Now, I am not going to say any more about closures, for this is something best explained by seeing code. Any words I add right now to define or describe what closures are will only serve to confuse things. In the following sections, we'll start off in familiar territory and then slowly venture into hostile areas where closures can be found. Onwards! Functions within Functions The first thing we are going to do is really drill in on what happens when you have functions within functions...and the inner function gets returned. As part of that, let's do a quick review of functions. Take a look at the following code: function calculateRectangleArea(length, width) { return length * width; } var roomArea = calculateRectangleArea(10, 10); alert(roomArea); The calculateRectangleArea function takes two arguments and returns the multiplied value of those arguments to whatever called it. In this example, the whatever called it part is played by the roomArea variable. After this code has run, the roomArea variable contains the result of multiplying 10 and 10...which is simply 100: [Image: ] (https://www.kirupa.com/html5/images/function_value_200.png) As you know, what a function returns can pretty much be anything. In this case, we returned a number. You can very easily return some text (aka a String (https://www.kirupa.com/html5/strings_in_javascript.htm)), the undefined value, a custom object, (https://www.kirupa.com/html5/a_deeper_look_at_objects_in_javascript.htm) etc. As long as the code that is calling the function knows what to do with what the function returns, you can do pretty much whatever you want. You can even return another function. Let me rathole on this a bit. Below is a very simple example of what I am talking about: function youSayGoodBye() { alert("Good Bye!"); function andISayHello() { alert("Hello!"); } return andISayHello; } We can have functions that contain functions inside them. In this example, we have our youSayGoodBye function that contains an alert and another function called andISayHello: [Image: the outer and inner functions visualized] (../images/visualization_inner_72.png) The interesting part is what the youSayGoodBye function returns when it gets called. It returns the andISayHello function: function youSayGoodBye() { alert("Good Bye!"); function andISayHello() { alert("Hello!"); } return andISayHello; } Let's go ahead and play this example out. To call this function, initialize a variable that points to youSayGoodBye: var something = youSayGoodBye(); The moment this line of code runs, all of the code inside your youSayGoodBye function will get run as well. This means, you will see a dialog (thanks to the alert) that says Good Bye!: [Image: ahhh!!! pop-up dialog!] (../images/goodbye_72.png) As part of running to completion, the andISayHello function will be created and then returned as well. At this point, our something variable only has eyes for one thing, and that thing is the andISayHello function: [Image: outer function go bye bye] (../images/var_something_72.png) The youSayGoodBye outer function, from the something variable's point of view, simply goes away. Because the something variable now points to a function, you can invoke this function by just calling it using the open and close parentheses like you normally would: var something = youSayGoodBye(); something(); When you do this, the returned inner function (aka andISayHello) will execute. Just like before, you will see a dialog appear, but this dialog will say Hello! - which is what the alert inside this function specified: [Image: oh, hi!] (../images/hello_72.png) All of this should probably a review. The only thing that you may have found new is realizing once a function returns a value, it is no longer around. The only thing that remains is the returned value. Ok, we are getting close to the promised hostile territory. In the next section, we will extend what we've just seen by taking a look at another example with a slight twist. When the Inner Functions Aren't Self-Contained In the previous example, our andISayHello inner function was self-contained and didn't rely on any variables or state from the outer function: function youSayGoodBye() { alert("Good Bye!"); function andISayHello() { alert("Hello!"); } return andISayHello; } In many real scenarios, very rarely will we run into a case like this. We will often have variables and data that are shared between the outer function and the inner function. To highlight this, take a look at the following: function stopWatch() { var startTime = Date.now(); function getDelay() { var elapsedTime = Date.now() - startTime; alert(elapsedTime); } return getDelay; } This example shows a very simple way of measuring the time it takes to do something. Inside the stopWatch function, we have a startTime variable that is set to the value of Date.now(): function stopWatch() { var startTime = Date.now(); function getDelay() { var elapsedTime = Date.now() - startTime; alert(elapsedTime); } return getDelay; } We also have an inner function called getDelay: function stopWatch() { var startTime = Date.now(); function getDelay() { var elapsedTime = Date.now() - startTime; alert(elapsedTime); } return getDelay; } The getDelay function displays a dialog containing the difference in time between a new call to Date.now() and the startTime variable declared earlier. Getting back to the outer stopWatch function, the last thing that happens is that it returns the getDelay function before exiting. As we can see, the code here is very similar to the earlier example. We have an outer function, we have an inner function, and we have the outer function returning the inner function. Now, to see the stopWatch function at work, add the following lines of code: var timer = stopWatch(); // do something that takes some time for (var i = 0; i < 1000000; i++) { var foo = Math.random() * 10000; } // invoke the returned function timer(); The full markup and code for this example looks as follows: