Skip to content
November 9, 2010 / lawrencebarsanti

Easy to Follow JavaScript Closure Example

The following example uses a closure – on the local variable value – to mimic a private variable.

// returns counter object
function createCounter() {
  var value = 0; // used by add, sub, val
  return {
    add: function(x) { value += x; },
    sub: function(x) { value -= x; },
    val: function() { return value;}

// create two counters
counter1 = createCounter();
counter2 = createCounter();

// use the counters
var val1 = counter1.val();
var val2 = counter2.val();
var val3 = counter1.val();

// the result: val1 is 14, val2 is 32, val3 is 10

The functions add, sub, and val are created and returned every time the createCounter function is executed. When they are created, the local variable value is in scope meaning it can be used by those functions.  Normally, when createCounter returns, the variable value would fall out of scope and be destroyed.  However, because value is used by the functions add, sub, and val it is not destroyed.  Instead, value remains available to those functions – this is a closure.

The functions add, sub, and val all have access to the same instance of value meaning changes to value are seen by all three functions. That is why val1 is 14 and val3 is 10.  If each function had its own private copy of value, the code would be useless because val would always return 0.

Each time createCounter is executed a new closure is created with its own instance of value. Because of this, calls to the functions in counter1 and counter2 do not interfere with each other. That is why val1 is 14 and val2 is 32.  This is powerful technique for controlling the scope of variables – try writing similar code without using a closure.

Once you understand this example, check out this detailed explanation provided at the Mozilla Developer Center.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: