Contact Us or call 1-877-932-8228


Closures are an extension of the concept of scope; functions have access to variables that were available in the scope where the function was created. All of the examples in the "Scope" section used closures to hold on to the value of a local variable declared in the enclosing function.

How to Lock in the Value of i? Use a Closure Combined With Pass-By-Value

In the previous section we saw how functions have access to changing variable values. In the demo below, a function is defined within a loop, using the looping variable inside the function. But, perhaps unexpectedly, the function "sees" the change in the variable's value even after the function is defined, resulting in all clicks alerting 5.

But, if we define a function that takes a parameter, and pass in the value of the looping variable. By definition, a method parameter is a local variable to the function. The passed-in value is captured and held for use when the click event occurs.

Code Sample:

<title>Using Closures</title>
<script src="../../jqy-libs/jquery.js"></script> 
<h1>Using Closures</h1>
// this won't behave as we want it to;
// every click will alert 5
for (var i=0; i<5; i++) {
	$('<p>click me</p>').appendTo('body').click(function() {

$('<hr />').appendTo('body');

// fix: 'close' the value of the parameter j inside createFunction
// since it was passed by value, each invocation will get its own copy
var createFunction = function(j) {
	return function() { alert(j); };

for (var i=0; i<5; i++) {
	$('<p>click me</p>').appendTo('body').click(createFunction(i));