Javascript Closure

A closure in Javascript happens when you return a function from inside a function. And This inner function retains access to the scope of the outer function.

var closureAlert = function() {
 var x = 0;
 var alerter = function(){
   alert(++x);
 }
 return alerter;
}

 var callClosure = closureAlert();

 var callClosure(); // 1
var callClosure(); // 2 and so on and so forth

callClosure is an example of a closure. It is defined as call to the function closureAlert(). closureAlert returns its inner function alerter. Thus the variable callClosure retains the scope of the inner function alerter. The alerter function in its turn increments the value of the variable x, which is defined within the scope of closureAlert().

callClosure stores whatever alerter returns. Closure is a foundational concept for practicing functional programming in JS.

Another Closure Example

  function counter() {
   var  n = 0
   return {
     count: function() { return ++n },
     reset: function() { n= 0; }
   }
 }

var myCounter = counter()

The function counter above returns an object with two properties(count and reset). The values of these properties are functions themselves and they modify the variable n which is defined within the local scope of counter.

The myCounter is a variable that calls counter(). counter() returns an object whose properties are functions.

myCounter.count() // 1

myCounter['count']() // 2  *Note the bracket notation. As it is an object if can also be called as such*

myCounter.reset() // 0

Closure Recipe A.K.A. How to create a Closure Function

// 1. create your parent function
 function checkScope(){ 

// 2.define some variables in the parent's local scope ( this can be accessed by the child function)

var innerVar = "local scope";

// 3. define a function inside the parent function. We call this a child.
     function innerFunc() {
          return innerVar;
     };

// 4. return that function from inside the parent function without calling it
     return innerFunc;

];

I am closing this blog post with another closure example:

  var add = function (num) {
   var  num1 = num;
   var addToNum1 = function(num2) {
     return num1 + num2;
   };
   return addToNum1;
 }

var add5 = add(5);
var add10 = add(10)
add5(2); // 7

add10(2); // 12

In var add5 = add(5); it is always storing num1 as 5.

To invoke add5(2) means to give the argument 2 to addtoNum1. addtoNum1 then sums num1 (5) to num2 (2), resulting add5(2) the number 7.

Enough of explanations. closingThisNow();

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s