Click here to Skip to main content
Click here to Skip to main content

Closures in JavaScript

By , 12 Jul 2012
 

Introduction

Definition - A closure is a function together with a referencing environment for the non-local variables of that function. << refer to link http://en.wikipedia.org/wiki/Closure_(programming)  >>

In JavaScript, using simple terms,  if we create a function inside another function, we are creating a closure. 

In most common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.  Keeping this in mind a closure can be considered as a stack-frame which is not deallocated when the function returns. 

Why use Closure

I have many asking me why closures are required. I will try to explain.

The scenario where I came across closures was while using Tabular Controls, File Objects etc. With Closures I could store the page indexes, row counts etc that I could re use for other client functions. With FSO i could have file paths , counts etc saved for later use. Its not only for complex client controls. Think of scenarios where your page has many controls and you are performing client side validations. Each time you acces a control by

document.getElementById("controlname")  

the whole page control tree is being searched. This can be avoided by using closures and saving the controls just once. Re-usability is a key advantage of closures.  Hope I have convinced few to atleast get to know Closures.

Using the code  

Take a look at the function below:

function sayHello(name) {
    var text = 'Hello ' + name; // local variable
    var sayAlert = function() { alert(text); }
    return sayAlert;
}

Now we call the function in the following way:

var say2 = sayHello("Sachin");
say2();

The function sayHello() returns a pointer to the function sayAlert().

Here when you declare a function within another function, then the local variables can remain accessible after returning from the function you called. This is demonstrated above; we call the function say2() after we have returned from sayHello(). Notice that the code that we call references the variable text, which was a local variable of the function sayHello().

Consider the function below:

function setupSomeGlobals() {

    // Local variable that ends up within closure
    var num = 666;

    // Store some references to functions as global variables
    gAlertNumber = function() { alert(num); }
    gIncreaseNumber = function() { num++; }
    gSetNumber = function(x) { num = x; }

}

The three functions gAlertNumber(), gIncreaseNumber(), and gSetNumber(x) have shared access to the same closure - the local variables of setupSomeGlobals() when the three functions were defined.

This can be checked by calling the functions one after the other.

Try the below sequence:

setupSomeGlobals() //value of num is 666 
gAlertNumber () //alerts 666 
gIncreaseNumber() 

gAlertNumber () //alerts 667 
gSetNumber (600) 
gAlertNumber () //alerts 600

If we call setupSomeGlobals() again, then a new closure (stack-frame!) is created. The old gAlertNumber, gIncreaseNumber, gSetNumber variables are overwritten with new functions that have the new closure.

Summary

  • A closure in JavaScript is like keeping a copy of all the local variables, just as they were when a function exited.
  • It is probably best to think that a closure is always created just on the entry to a function, and the local variables are added to that closure.
  • A new set of local variables is kept every time a function with a closure is called (given that the function contains a function declaration inside it, and a reference to that inside function is either returned or an external reference is kept for it in some way).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

SachinKumarK
Web Developer
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5professionalPrasad Khandekar23 May '13 - 3:50 
GeneralMy vote of 4membergerm1316 Jul '12 - 17:10 
SuggestionMy vote of 5, but... a couple of notesmvpSergey Alexandrovich Kryukov28 Jun '12 - 12:32 
GeneralRe: My vote of 5, but... a couple of notesmemberSachinKumarK12 Jul '12 - 3:36 
QuestionWhy?memberFred_Smith26 May '07 - 7:20 
AnswerRe: Why?memberRichardGrimmer28 May '07 - 23:15 
GeneralRe: Why?mvpSergey Alexandrovich Kryukov28 Jun '12 - 12:27 
Of course. Good answer to the question "why". It is very useful, and especially useful to understand. My 5.
 
—SA

Sergey A Kryukov

GeneralRe: Why?memberTheFisch16 Jul '12 - 10:37 
AnswerRe: Why? [modified]memberSachinKumarK31 May '07 - 22:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 12 Jul 2012
Article Copyright 2007 by SachinKumarK
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid