What is JavaScript closure and how it works?

What is closure in JavaScript?

closure is the combination of a function and statically saved all parent scopes using [[Scope]] property.

Why we need closure?

In ECMAScript the functions are considered as first-class object. This means a function can be passed as a parameter to a function and a function can be returned from a function. When a function is passed to a function or returned from a function both the cases we get into scope issues (functional arguments issue). To solve this issue the closure is introduced in JavaScript.

Does every function creates closure?

Every JavaScript function creates closure on function activation. Lets take a look how that happens. According to the closure definition the function code and it’s [[Scope]] property are the key for closure. Lets look at this example:

function  getUsername() {
    var username = 'Joe';
    console.log(username);
}
getUsername();
console.dir(getUsername);

Explanation of the above example

The above code block is simply a function definition. We have declared a variable called username and doing console.log of that name. Now if we call the function username from global context then we will see it logs the name ‘Joe’. Lets take a look at the hierarchical listing of the function getusername.

Output of console.dir


We can see that the function getUsername does have a [[Scope]] property. For this function the [[Scope]] property is pointing to global object. Using this global object anything can be accessed inside getUserName function. Because of this global object it’s not interesting for closure.

Lets modify the code a bit.

function getUsername() {
    var username = 'Joe';
    return function () {
        console.log(username);
    };
}
var username = 'Jenny';
var nameFn = getUsername();
nameFn();
console.dir(nameFn);

Explanation of the above example

We have a function definition called getUsername and inside the function we declared a variable username. Then we are returning a function as the return of that function. We can see that the function we returned has printed a free variable. A free variable is a variable that is not declared inside that function but has a reference to it’s parent scope. As the function has a free variable, it added a closure type object along with global object in it’s [[Scope]] object. We can see visually a closure type is added to the [[Scope]] property. When the function is returned this [[Scope]] property goes along with the function. When we call this fuction from global context it get it’s from [[Scope]] property. Not from the global context.

Output of console.dir

Share