AppDividend
Latest Code Tutorials

Javascript Closure: How to Use Closure in JavaScript

1

Javascript Closure is the aggregate of functions clumped together with the references to its surrounding environment. It gives you an outer function’s scope from an internal function. Scopes are contexts of variables. Every object has a link to the scope chain, local first, then parents, and then Global Scope. The Closure allows a function to carry its scope from another context, or we can say another lexical scope.

Javascript Closure

A Closure is the javascript feature that happens. We do not worry about it. Javascript engine creates the Closure, and we have its advantage to use it.

What is closure in Javascript
What is Closure in Javascript

Example # 1

//main.js

function work(name){
    return function (topic) {
        console.log(`What is ${topic} in ${name}`);
    }
}
work('Javascript')('Closure');

If you are directly running the above code in the browser, you might face the following issue.

Possible Errors

  1. You can get any syntax errors.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put the above code in the main.js file

Here in the example, I have used Template Strings, which is an ES6 feature.

The output of the function lexical is “What is Closure in Javascript.”

Now, let me dive in deep.

First, we have called the function work and pass an argument of the name. Now, that lexical function also returns a function that also takes an argument of the topic. But wait inside the work function, there is one more function, and that function logs the output, and in the output, we also have access to the name variable.

So in the console, we can see the complete sentence like “What is Closure in Javascript.” Insider function scope is not limited to that function, and so the Concept is called Closure because It has still access to that an outer name parameter scope.

The returned function always has access to the scope of outer lexical scope or contexts. It means that when you call a function that also returns a function, then the first called function’s variables are always accessible to the internal function. Closures are a powerful mechanism to create unique design patterns in Javascript. 

We can also write the above example with the following code.

// main.js

function work(name){
    return function (topic) {
        console.log(`What is ${topic} in ${name}`);
    }
}
var hold = work('javascript');
hold('Closure');

Outer Lexical Scope

From the first call to the function, the execution environment builds something like this.

Outer Lexical Environment Scope
Outer Lexical Environment Scope

Inner Anonymous Function

Now that the execution environment is destroyed, the parameter name is still there, and the environment is destroyed. Now a new inner function environment is created, which is an Anonymous Function. 

That function still has access to An Outer Lexical Environment Scope. So in the outer environment name variable is still there so that Anonymous Function has access to the name variable and print in the console like “What is Closure in Javascript.”

Inner Anonymous Function
Inner Anonymous Function

Example # 2

//main.js

function factory(){
   var products = [];
   for(var i=0; i<2; i++){
       products.push(function () {
           console.log(i);
       });
   }
   return products;
}
var soap = factory();
soap[0]();
soap[1]();

The output of this example is relatively not familiar, but it is a 2 2.

When soap[0]() is called, the external context variable is always 2 because, in the loop, the condition is false at i < 2, so at that, the value of i is 2, and at call time, we want to print the value in the console so, It always writes 2. Same for the soap[1]().

Finally, the Javascript closure example is over.

1 Comment
  1. Amit Parmar says

    thanks for the post

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.