AppDividend
Latest Code Tutorials

What is Closure in JavaScript?

317

Get real time updates directly on you device, subscribe now.

Hey Webbies, In today’s AppDividend Tutorial, I have briefly described What is Closure in Javascript?

Closure

A 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 scope chain, local first then parents and then finally Global Scope. The Closure allows a function to carry its scope from another context or we can say another lexical scope.

A Closure is the javascript feature that just 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 directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  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 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 lexicle 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 lexicle function also return a function which also takes an argument of the topic. But wait inside work function there is one more function, and that function logs the output, and in output, we also have access to 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 first called function’s variables are always accessible to the internal function. Closures are the powerful mechanism to create extraordinary design patterns in Javascript. We can also write 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 execution environment is destroyed but the parameter name is still there, and the environment is destroyed. Now new inner function environment is created which is an Anonymous Function. That function has still access to An Outer Lexical Environment Scope. So in outer environment name variable is still there so that Anonymous Function has access to 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 quite 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]().

Related Posts
1 of 5

Leave A Reply

Your email address will not be published.

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