Understanding JavaScript Closures

Print Friendly

helloWorldJS

Javascript closures are considered an advanced topic in Javascript and understanding closures is essential to master Javascript. After reading this article, app developers will have an understanding of the following:

  • What are Javascript closures
  • How are Closures useful
  • Why to use Closures
  • How to use Closures
  • Javscript Closure Examples

  • JavaScript is a functional language unlike imperative languages like C/C++/Java. Using Javascript it is possible to assign a function to a var, pass one as an argument to another function, and return a function with the return keyword. Even a function can be declared inside another function, with all the scoping rules. So if there is a function within another function, the inner function has access to variables of the outer function.

    One of the situation where closures play a role is when a function definition is nested within a parent function that returns the nested function object as the value of the parent function. In this situation, the nested function retains references to the local variables in the parent function, even after the parent function finishes executing.

    To be very simple if a function is defined in another function and it has access to the outer function’s context even after the outer function returns it is said to be a closure function.

    function parentFunction(msg) {
      var someString = 'World!';
      var content = document.getElementById('content');
      function nestedFunction() {
        content.innerHTML = msg+ ': ' + someString;
      }
      nestedFunction();
    }
    
    parentFunction("Hello");?
    

    In the above example the nested function (nestedFunction) have access to the local variables of the function it is defined within (parentFunction) and retain references to those variables even when the inner function has a longer lifetime than the parent function.

    Another example where a function keyword is present within another function and the inner function has access to variables of the outer function:

    function foo(x) {
      var tmp = 3;
      function bar(y) {
        alert(x + y + (++tmp));
      }
      bar(10);
    }
    foo(2);
    

    Here call to function foo with an argument 2 will always alert a total value of 16, because bar can access the value of variable x which was defined as an argument to foo, and it can also access variable tmp from foo. That is a closure. A function doesn’t have to return in order to be called a closure. Accessing variables outside of a function’s immediate lexical scope creates a closure. The inner function will close-over the variables of function foo before leaving. This is an example of functional scoping: in JavaScript, the scope of a variable is defined by its location within the source code, and nested functions have access to variables declared in their outer scope.

    Another Example to try closures in JS,

    feel free to fork it and and play with it at jsFiddle.

    It’s important to understand that the nested function retains a reference to the variables, not just the value. The above example in jsFiddle shows code where the parent function defines a message variable then a nested function, and then it changes the value of the message variable.

    Finally, Javascript closure can be summarized as:

  • A closure is a binding of some data to a function and storing it as a variable to use later
  • A closure is a stack-frame which is not deallocated when the function returns.
  • A closure is a function to which the variables of the surrounding context are bound by reference.
  • A special type of object that combines function and the environment in which the function was created, where environment is local variable of function and input parameters within the function.


  • There is a great video tutorial which discuss about JS closures as well at MSDN . You may also refer to Mozilla Developer Network.

    I hope this gives you an idea about JS closures. Since it is an advanced topic in JS, it may take some time to understand where to implement this feature in your code. Understanding while doing is easier rather than simply reading an explanation, so it would be a great idea to play with the jsFiddle and other code examples used in the post.

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)

    Comments

    1. globalob says:

      Good article . Will definitely copy it to my blog.Thanks.

    2. obalus says:

      Thank you for this valuable post.

    http://www.windowsvj.com/outlet