Click here to Skip to main content
Licence CPOL
First Posted 16 May 2007
Views 15,980
Bookmarked 10 times

Closures in JavaScript

By | 24 May 2007 | Article
An introduction to closures in JavaScript.

Introduction

A closure is the local variables for a function that are kept alive even after the function has returned.

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

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().

In most common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.

In JavaScript, if 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



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

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionWhy? PinmemberFred_Smith7:20 26 May '07  
AnswerRe: Why? PinmemberRichardGrimmer23:15 28 May '07  
AnswerRe: Why? [modified] PinmemberSachinKumarK22:04 31 May '07  

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 25 May 2007
Article Copyright 2007 by SachinKumarK
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid