Closure in JavaScript through examples

javascript closureWhat is Closure?

A Closure is a named or anonymous function defined within the context of an object or any other function, which preserves and access to the context where it was declared.

To understand closure, it requires you to be familiar with basic JavaScript concepts, such as scope of variables and functions.

A closure is a named or anonymous function:
javascript closure
This is not a closure:

//Named function
function greetings() { //this is not a closure function.
    return ‘Howdy’;
}

//anonimous function
var greetings2 = function () { //this is not a closure function.
    return ‘Hello’;
}

greetings(); //Shows Howdy.
greetings2(); //Shows Hello.

Basically a closure function is a function that can access to the variables declared in the outer context, including global variables.

 

book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

Closures in action.

Here is an example that will help you recognize when you need to use a Closure.

How to do it correctly.

Suppose you want to use a variable to count and want to create a function to increment the count variable.

var counter = 0;
function increase() {
    counter += 1;  // increment its current value.
    console.log(counter);
}

increase();
increase();
increase();

 // The counter is now equal to 3.

Here we have a solution, but has flaws; the counter variable is global, any script on the page would have access to it and could change it without calling the increase function .

We need to make sure that the counter variable is only modified by the increase function.

Therefore, move the definition of the variable inside the function, so no one can modify it without calling the function increase:

function increase() {
    var counter = 0;
    counter += 1; // increment its current value.
    console.log(counter);
}

increase();
increase();
increase();

// We expect the value of the count variable is 3, but it will be 1.

Now the counter variable is not accessible from the outside (now is protected), but this wong work properly because every time you call the function it will define the variable account.

We need to create an internal function to solve this:

var increase = (function() {
    var counter = 0;
    return function () {
        return counter += 1;
    }
 console.log(counter);
})(); //* IIFE Auto-invoked function.

increase();
increase();
increase();

// The counter is now equal to 3.

*IIFE Immediately Invoked Function Expression (see Encapsulation in JavaScript).

A common mistake

Here’s an example of misuse of Closure function. Suppose we have the following code:

function count() {
     var i;
     for (i = 1; i <= 3; i ++) {
         setTimeout (function () {
             console.log ('The count value is '+ i);
         }, 1000); // 1000 milliseconds = 1 second
     }
}
count();

And this is how you can solve it:

function count() {
     var i;
     function display(j) {
         return function () {
             console.log ('The counter value is ' + j);
         }
     };

     for (i = 1; i <= 3; i ++) {
         setTimeout (display(i), 1000);
     }

}
count();

I’m not going to explain in detail how this is solved, I’ll leave it to you, if you understand what happened then you understand JavaScript closure. 😉

Other references:

https://developer.mozilla.org/es/docs/Web/JavaScript/Closures
http://javascriptissexy.com/understand-javascript-closures-with-ease/
http://www.w3schools.com/js/js_function_closures.asp