javascript

Closure in Javascript a Complete Definition

The closure is an intriguing concept in Javascript. It is a must-know topic for any beginner to advanced Javascript developer.

In this article, I am going to discuss closure in Javascript.

What is the closure in Javascript

To understand closure, we need to understand the scope first.

Closure and scope are related closely, and because of that, it gets confusing very often.

Let suppose there is a variable within a function. Now, the function body is the local scope for that variable. 

If we declare another variable right outside the function, then that variable becomes a global variable to our function. And, that global variable is accessible within our so-called function body.

Ideally, after the execution of any function, the execution context clears local variable reference. That means, as soon as we process any scope, the variable references gets released.

Now imagine a scenario where our local function is accessing a global variable, and we are saving a reference to our local function in another variable.

Closure example in Javascript

For a better understanding, let’s take a look at the below code and try to map your thought.

function person() {
   var userName = 'John';
    function getName() {
      console.log(name);
    }
    return getName; // returns a function
 }
 var p = person();
 p(); // This is calling getName() 

Look closely, the function person() is returning another function getName().

So, getName() is our function from the above discussion. And getName() is accessing the global variable userName.

Initially, everything looks fine. Now, take a look at the second last line in the above code. 

var p = person();

After this line gets executed, the variable p holds a reference to the getName() function definition. And the outer function person() gets cleared out of the execution context. 

Ideally, from the definition of Scope, the variable userName should get wiped out along with its container function person().

But in the next line, when we call p() then, internally the getName() function’s body gets called. Which eventually tries to access the global variable userName.

Conclusion

If we go by the definition, then we should get an error message. But we don’t. Because here comes the closure playing its role. And, because of this feature, we see the result instead of an error.

Leave a Comment

ten + = twenty