Beauty of Closure in Java Script


Closure is one of the good parts in JavaScript. Its an amazing way to enable access of local variables from parent function scope, irrespective of the context in which function was invoked. Wait, Instead of getting into jargon about closure, let me just illustrate with a few examples.

Problem statement:
Write a function which will take a digit as input and output verbal representation of the same.

Solution 1:
var numberMapping = [‘zero’,’one’,’two’,’three’,’four’,’five’,’six’,’seven’,’eight’,’nine’];
function getNumber(number) {
    return numberMapping[number] ? numberMapping[number] : ‘Inavlid input’;
}

// getNumber(1)
// “one”

// getNumber(12)
// “Invalid input”

Lets try to analyze this, we have a global array which holds verbal representation of all digits, and then we’re using this array to return corresponding output of given number. Problem with this approach is, numberMapping array is just dangling in global namespace, means it could be modified anywhere in code. And ofcourse, if modified it will give incorrect result. So this approach is bad. In JavaScript always try to avoid global variables to the extent possible. Also this might create a problem in minification as most of the minifiers tend to change the variable names to shorter versions.


Solution 2:
function getNumber(number) {
    var numberMapping = [‘zero’,’one’,’two’,’three’,’four’,’five’,’six’,’seven’,’eight’,’nine’];
    return numberMapping[number] ? numberMapping[number] : ‘Inavlid input’;
}

// getNumber(1)
// “one”

// getNumber(12)
// “Invalid input”

Oh! so we just take the variable inside getNumber function making it local. It works fine and solves the problem we faced in solution 1. But this still isn’t the best approach. Because every time getNumber is called, numberMapping array will be initialized and memory will be allocated to it. So this is nice but not the optimum solution.



Time to use closure:
var getNumber = (function() {
    var numberMapping = [‘zero’,’one’,’two’,’three’,’four’,’five’,’six’,’seven’,’eight’,’nine’];
    return function (number) {
        return numberMapping[number] ? numberMapping[number] : ‘Inavlid input’;
    }
})();

// getNumber(1)
// “one”

// getNumber(12)
// “Invalid input”


OK, so this looks a bit complex. What we’re doing here is executing an anonymous function and storing the returned value in a variable named getNumber. In this particular case we’re returning a function. And yes, we can do this in JavaScript! This approach solves the problem we faced in solution 1 by encapsulating numberMapping array. Also as the upper function will only be executed once, hence numberMapping array won’t be initialized every time we call getNumber. And the inner function has access to numberMapping variable because of the beauty of closure!


To sum it up:
This approach is helpful in many conditions, the most common one is while trying to write object oriented code in JavaScript. using ‘prototype’ or ‘this’ for creating classes does not really fit in overall code ethics of JavaScript. if you use ‘this’ or ‘prototype’ for creating classes, implementing singleton class is not an option. Whereas if you use closure you can use the same style of coding throughout the code base. Using closure in javascript definitely helps in writing beautiful code.