1st Minute: What is a closure in Javascript?

A closure is not really a thing. It is just a term we use to describe what happens when we have a function that has access to outside variables other functions cannot access.

Outside variables are sometimes referred to as non-local variable.

Here is a simple example of closure in JavaScipt.

function cat(){

    var nyan = "meow";

    function speak(){

        alert(nyan);

    }

    speak();

}

Now everytime you do cat(), a new variable, nyan, would be created. And nyan is only accessible by the speak function inside cat.

cat(); //alerts "meow" because speak() is invoked

alert(nyan); //error: nyan is undefined

Here is another example of closure.

function cat(){

    var nyan = ["meow","I am a cat"];

    var x = 0;

    var speak_and_change_x =  function(){
        //alert either "meow" or "I am a cat"
        //based on x
        alert(nyan[x]);

        //change x
        x = (x+1===2)? 0 : 1;
    };

    return speak_and_change_x ;

}

Now when you invoke cat, 3 variables will be created: an array nyan, an integer x, and a function speak_and_change_x. Both nyan and x can only be accessed by function speak_and_change_x inside cat.

cat(); //nothing will be alerted.

cat()(); //alert "meow";

Since you are just returning speak_and_change_x, rather than invoking it using (), nothing will be alerted when you write cat(). However, writing cat()() will alert ("meow") because it is equivalent to invoking the function cat returns - and that is the same as speak_and_change_x().

Rather than writing cat()() to invoke the function, normally what we do is to store what cat() returns into a variable.

var Archy = cat(); //since cat() returns speak_and_change_x, Archy is now speak_and_change_x;

//now invoking Archy() will be the same as invoking speak_and_change_x()

Archy(); //alerts "meow"

Archy(); //alerts "I am a cat"

Archy(); //alerts "meow"

Archy(); //alerts "I am a cat"

Note: when returning a function, you shouldn’t put () behind it. The moment you put () behind a function, you are invoking/invoking it.

var a = function (){ return 6 };

var b = a(); //b is 6.

alert(b); //6 will be alerted;

alert(b()); //error: b is not a function

var c = a; //c is a function

alert(c); //the entire function will be alerted

alert(c()); //alert 6.

Click here if you are curious what invoking alert(c) will do in the code above.

● ● ●

Bonus: Ternary Operator

In the example above you can see that I am doing something like this:

x = (x+1 === 2)? 0 : 1;

This is a short way of writing

if( x+1 === 2 ){
    x = 0;
}else{
    x = 1;
}

The way it works can be visualized in this form:

x = (condition)? if true : if false;

Bonus: Strict Comparison Operators (=== and !==)

The === in the code above is known as a Strict Comparison Operator. It is slightly different from ==. When we compare two variables like this: a === b, the JavaScript engine will first look at the variables’ types, and if they are not the same type, false will be returned immediately.

(0 === null) //false;

(0 === "0") //false;

(0 === []) //false;

(0 === 0) //true;

If we compare two variables using ==, a type conversion would happen before the comparison occurs.

(0 == null) //true; because JS engine has converted null into integer 0

(0 == "0") //true; because JS engine has converted the string "0" into integer 0

(0 == []) //true; because JS engine has converted the empty array [] into integer 0

(0 == 0) //true;

Therefore, in terms of performance, === would be slightly faster. The other strict comparison operator is !==, which is simply the inverse of ===.

(0 !== 0) //false;

(0 !== null) //true;

● ● ●

2st Minute: More on Closure in JavaScript

When you create a closure, instead of returning a function, you can return an object. Here is another example of closure.

var Archy = (function(){
    var nyan = ["meow","I am a cat"];
    var x = 0;
    var a =  function(){
        alert(nyan[x]);
    };
    var b = function(){
        x = (x+1===2)? 0 : 1;
    };
    return {
        speak: a,
        transform: b,
        name: "Archy"
    }
})();

In the example above, by returning an object, you will be able to return 2 functions that can access nyan and x, which other functions has no access to.

alert(nyan[x]); //nyan is undefined, x is undefined.

Archy.speak() //alerts "meow"

Archy.speak() //alerts "meow"

Archy.transform() //this changes the value of x that Archy.speak() has access to.

Archy.speak() //alerts "I am a cat", because x has been changed to 1.

alert(Archy.name); //alerts "Archy"

Functions in the form function(){...} is known as anonymous function. One cool thing in JavaScript is that functions are actually not required to have names.

By having a function like this (function(){...})() (enclosing it with brackets and putting another pair of brackets behind), we are basically invoking this anonymous function. The () behind can also be used to pass parameters into the function, just like what can be done using () behind a function name like this alert("nyan").

(function(){ alert("x") })(); //alert "x"

(function(a){ alert(a) })("x"); //alert "x"

One common practice in Java script is to pass commonly used variables into anonymous function as parameters for quicker access. By passing a variable into a function, you would be able to access it locally instead of globally when you are inside the function, and thus it would be relatively faster.

(function(){ console.log(window); })(); //accessing global variable.

(function(window){console.log(window); })(window); //accessing local variable.

When you surround statements (e.g. a function statement: function hi(){}) in brackets (i.e. you have (function hi(){})), you are turning them into expressions (in this case it’s known as immediately-invoked function expression (IIFE)) and you can do all sort of things with expressions, similar to how you can do all sorts of things with variables.

var d = 1 < 0; //d has a boolean value of false.

d.toString(); //d has been converted into a string.

alert(d); //alerts "false"

var a = (1 < 0).toString(); //(1< 0) is being interpreted as an expression.

alert(a); //alerts "false";

(function hi(){alert(a)}).call(); //alerts "false";

(function hi(){alert(a)})(); //alerts "false";

function hi(){alert(a)}.call(); //syntax error

function hi(){alert(a)}(); //syntax error

3rd Minute: Design patterns in JavaScript

The example above where we create a closure and return an object is an example of a design pattern in JavaScript known as The Module Pattern.

There are many design patterns in JavaScript. Different design patterns are just different ways of writing codes. The Module Pattern, for example, uses closure to create the illusion of a class object (or a class instance), something that JavaScript doesn’t really provide (since JavaScript implements prototype-based OO). Using The Module Pattern, one would be able to have public and private functions and variables in an object (as if it is an instance of a class in class-based OO).

In this case, x and nyan are private variables, while name is a public variable and speak() and transform() are public functions. In class-based OO language, when something is public, it simply means that it is globally accessible. When something is private, only the instance and class functions (In this case there isn't a class function) are able to access it.

Now let’s move on to The Singleton Pattern, another beginner design pattern that makes good use of closure. The Singleton Pattern is like an upgrade version of The Module Pattern. Besides creating an illusion of a class object, it creates an illusion of a class function that either constructs the object (an instance of the class) or returns an already constructed object.

var Archy = (function(){

    function cat (obj){
        var nyan = obj.nyan,
        x = obj.x;
        this.speak = function(){
            alert(nyan[x]);
        };
        this.transform = function(){
            x = (x+1===2)? 0 : 1;
        };
    }

    var instance;
    var _static = {
        name: "Archy",
        get_cat: function(obj){
        if(instance === undefined){
            instance = new cat(obj);
        }else{
            console.log("instance already created. nyannannn.");
        }
        return instance;
        }
    }
    return _static;
})();

var nyancat = Archy.get_cat({nyan: ["meow","I am a cat"], x: 0}); //it creats an instance
nyancat.speak(); //alerts "meow";
nyancat.transform();
nyancat.speak(); //alerts "I am a cat";
var mycat = Archy.get_cat(); //"instance already created. nyannannn."
mycat.speak(); //alerts "I am a cat";

Basically, in the Singleton Pattern, we restrict instantiation of a class to a single object.

(From the example above:)

var instance;
var _static = {
        name: "Archy",
        get_cat: function(obj){
        if(instance === undefined){
            instance = new cat(obj);
        }else{
            console.log("instance already created. nyannannn.");
        }
        return instance;
        }
    }

Here we can see that nothing will happen to the variable instance. And it would be returned if instance is not undefined.

Conclusion: in The Singleton Pattern, the object/instance can only be accessed using the Archy.get_cat() function. So Archy is acting like the agent of the cat. There is no other way to get the cat unless you ask Archy. And Archy would create the cat for you the first time you ask for the cat. After that Archy would just keep giving you the same old cat.

Thrrp.

If you'd like to learn more about JavaScript's design patterns, here is a great book written by Addy Osmani.