≡ Menu

How to Use Javascript Closures Explained with Example Code

Javascript is a powerful scripting language for developing dynamic web pages.

While it has always been a powerful client side scripting language, it has also evolved as a server side scripting language with the introduction of Chrome V8 engine based Node.js javascript framework. For some, Javascript is serving as a one stop solution for both web/mobile client side and server side scripting.

One of the scripting constructs used in advanced javascripting is called Closures.

It plays a prominent role in object oriented javascripting construct. Before we dig deep into it, let us first understand variable scoping in javascript.

Variable Scope in Javascript

In javascript a variable can have global scope or local scope. A variable declared without the ‘var’ keyword always have global scope whereas if a variable will be local to a function if it is declared with ‘var’ keyword.

For example, in the script below variable y and b are always having global scope because it is not declared using var keyword.

However, variable x is global to these lines as it is declared in the global scope and variable a is local to the ‘function example()’.

/* Global variable in this code as it is in outter-most (global) scope.  */
var x = 0;    

// Global variable as keyword var is not used.
Y=0;

function example(){

  // local variable of function example()
  var a = 0;     	

  /* Global variable as keyword var is not used, even though it is in function. */
  b = 0;	 		
}

Javascript Closures

Closure is a function, which have the references of the variables, which are in the same scope as the function itself. It remembers the reference even after it is returned out of the scope.

In the example below, the inner function remembers the reference of outterVar as they both are in same scope.

function outterfunc( ){

  var outterVar = 10;
  
  // Closure having reference of outterVar	
  function inner(){	  		
  
  	alert( outterVar );
  
  }
  
  inner( );
  
}
 
/* It will alert the value 10 as function inner can access outterVar */
outterfunc( );           

We can script the above lines giving same results, in a self-invoking way as follows:

(function outterfunc( ){

  var outterVar = 10;
  
  // Closure having reference of outterVar	
  function inner(){	                
  
  	alert( outterVar );
  
  }
  
  // calling inner function here
  inner( );     			

// It will alert the value 10 as function inner can access outterVar
})();		

Lets take one more example to understand how it behaves when ‘function inner’ is returned out.

function outterfunc( ){

  var outterVar = 10;
  
  // Closure having reference of outterVar	
  function inner(){	  
  
  	alert( outterVar );
  
  }
  
  // returns the variable out of the scope of outterfunc
  return inner;    

}

var innerfunction = outterfunc();

/* It alerts the value as 10 because the closure function ( 'function inner') */
/* still has the reference of the outterVar, although it has been returned out */
innerfunction();     

In the script above the inner function has the reference of the outterVar, ever after it has been returned out the scope of outterfunc.

Closures have been highly used while scripting using Node.js and while implementing module javascript design pattern.

One of the good and most widely used example of javascript closure is while using jQuery.

Here is an example:

$(document).ready(function(

  var name = “thegeekstuffdotcom”;
  
  //  Closure having access to name variable
  $('li').click(function(        
  	alert(name);
  ));

));
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Philippe Petrinko May 28, 2014, 4:37 am

    Hi ,

    CMIIAW, but did you mis-typed your variable names?

    Once, your code “outterVar” and then “outterVariable”. Did I got this wrong or is it an error?

    –P

  • Robin May 28, 2014, 8:14 am

    Yaa, it is a typing mistake. ….

  • Ramesh Natarajan June 2, 2014, 12:54 am

    @Philippe, @Robin,

    Thanks for pointing out the typo. It is is fixed now.

  • antonio June 17, 2014, 3:21 am

    nice stuff !!!!

  • Pratik July 1, 2014, 12:28 am

    Thanks Ramesh