Wisdom of Helios

Javascript closure tutorial with example

Leave a comment

A closure in JavaScript is like keeping a copy of all the local variables, just as they were when a function exited.
Simply accessing variables outside of your immediate scope creates a closure.

Example 1 :
Simplest Closure example

var a = 3; // global varibale
function t() {
console.log(a); // will output 3
console.log(b); // will output 4
}
var b = 4; //// global varibale
t();

Example 2 :
Here a closure is formed, because f2 funtion can access the “temp” which was defined
as an member variable of f1. To become a closure function does not need to be returned all the time

function f1(a)
{
  var temp = 0;
  
  function f2(b)
  {
    alert(++temp); // will alert 1
  }
  
  f2(3);
  
  }
  
f1(5);

Example 3 :
Below code snippet also creates closure,
f2 function can still refer to temp even though it is no longer directly inside the scope.
However, since temp is still hanging around inside cls closure, it is also being incremented.
It will be incremented each time you call cls().

  
function f1(a)
{
  var temp = 0;
  
  return function f2()
  {
    alert(++temp); 
  }
  
}
  
var cls =  f1(5); // return function has been coppied
cls() // closure formed !!!!!  temp = 1;
cls(); // temp = 2;
cls(); // temp = 3;

Example 4 :
A closure is a stack-frame which is not deallocated when the function returns .
The three functions have shared access to the same closure — the local variables of s() when the three functions were defined.

Note that in the below example, if you call s() again,
then a new closure (stack-frame!) is created. The old sShow, sIncrease, sSetNumber
variables are overwritten with new functions that have the new closure.
(In JavaScript, whenever you declare a function inside another function,
the inside function(s) is/are recreated again each time the outside function is called.)

  
function s() 
 {
    // Local variable that ends up within closure
    var num = 666;
    // Store some references to functions as global variables
    sShow = function() { alert(num); }
    sIncrease = function() { num++; }
    sSetNumber = function(x) { num = x; }
}

s();
sIncrease();
sShow(); // will alert 667 as sIncrease() is called earlier 
		//	and now num = num+1. 

sSetNumber(10);
sShow();  // will alert 10 as sSetNumber() is called earlier 
		//	and now num = 10. 
        
var oldVal = sShow(); // alert 10 as num is set to 10 earlier.
s() // new closure (stack-frame!) is created. All inner functions will 
    // generate new closures.
    
sShow(); // alerts 666

Example 5 :
This example shows that the closure contains any local variables that were declared inside
the outer function before it exited. Note that the variable greet is actually declared after
the anonymous function. The anonymous function is declared first; and when that function is
called it can access the greet variable because greet is in the same scope
(JavaScript does variable hoisting). Also yourName()() just directly calls the function reference
returned from sayName().

function yourName(name) {
    var sayName = function() 
                   { 
                     alert(greet); // still can access greet, As 
                   }             // inner function has access on all local variables  
                              //of outer function. 
         var greet = 'Hello ' + name; 
          return sayName; 
         } 
      yourName("Max")();

Hopefully you have enjoyed this post. Happy coding. 🙂

Author: Munir

I'm good for nothing

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