Basic Understanding of Closures in Javascript.

A very straightforward way of understanding closures in javascript is that closures are what that gives your javascript functions access to the scope of your outer function.

Let us first quickly understand about Lexical scoping in the easiest way possible. Now, Javascript has something called ‘Lexical Scoping’. What this lexical scoping does for us is that we do not need to pass the outer declared variable inside our function. It is important to understand the functional scope and block scopes in javascript before you jump onto understanding closures(As we have not discussed it here.). Something you should be familiar with even if you have code in other languages.

Taking a simple example.

function first(){
    var _first = 1;
    function second(){
        var _second = 2
        console.log(_first)
        console.log(_second)
    }
    second()
}
first();

The above code when executed will print

1
2

So, A closure will give you access to these scopes.

  • Its own scope. The variables defined inside the function in the current context
  • Access to member variables defined in the outer function.
  • Access to the global variable

A closure therefore could be said to be a pairing of a function with its outer scope. One of the most important use cases of closure is to make private methods a feature that javascript does not provide out of the box. Take an example

function a(x) {
    var privateVariable = x;
    return {
        get: function(){
            return x;
        }
    }
}

let b = a(5)
console.log(b.get())

In the above example, you can not access our addby5 function from outside our function. To access/use our privateVariable you need to use the get wrapper provided to you. These wrappers are nothing other than being closures as well. Closures that share the same scope. It is due to the pairing of the function with its outer scope that gives them access to privateVariable. if you added another function wrapper let’s say a set function and then call it wouldn’t change the value of our private function as both of them have a different versions of the privateVariable.

example:

function a(x) {
    var privateVariable = x;
    return {
        addby5: function () {
            return x + 5;
        },
        get: function(){
            return x;
        }
    }
}

let b = a(5)
console.log(b.get())
console.log(b.addby5())
console.log(b.get())

It would result to.

5
10
5

Looking at what results we got. The last function returned us 5 and not 10 because each of these closures referenced a different version of our private variable. Some other use cases of closures are using them to create function factory where the outer function is responsible for creating a function that is somehow related to the outer function.

for example:

function getTitle(x) {
    return function (gender) {
            var title = gender.toLowerCase() == 'm' ?'Mr.': 'Miss.'
            return title + x;
        }
}

let b = getTitle('Sam');
console.log(b("m"));

Here we created a function that attaches the correct title to a person. You can create multiple such function that use the same data but the operation they perform on it are unique.

Closures is a topic in javascript that has been rather made complicated. Here I tried to cover up Enough Information about closures that would get you understanding what a simple concept closures are and what their popular use cases are.

Leave a Reply