What is a closure In JavaScript?

In this blog, we’ll learn closure which is what many developers think most complicated topic in javascript. If you’re preparing for an interview for MNC companies then it’s 100% probabilities that they will ask you about closures.

so let’s start and see what the closures is?

YouTube

What is a closure

Rather than directly going to its definition, I would like to proceed with the practical example of closure. After seeing this example you’ll completely clear about closure.


          var globalVar = "xyz";  
          (function outerFunc(outerArg) {     
              var outerVar = 'a';          
              (function innerFunc(innerArg) {     
                  var innerVar = 'b';          
                  
                  console.log(         
                      "outerArg = " + outerArg + "\n" +         
                      "innerArg = " + innerArg + "\n" +         
                      "outerVar = " + outerVar + "\n" +         
                      "innerVar = " + innerVar + "\n" +         
                      "globalVar = " + globalVar
                  );          
                })(456); 
          })(123);

        

Let’s understand the above example now.

we’ve declared one global variable first after then created two functions where outerFunc is the parent function and innerFunc is an inner function. you’re thinking that why I’m wrapping function in parenthesis so it’s nothing but IIFE(Immediately Invoked Function Expression). IIFE(Immediately Invoked Function Expression) is a function that runs as soon as it is defined.

We’re passing 123 value as a parameter to our outerFunc function and 456 value as a parameter to the innerFunc function. Inside our innerFunc function, we’re printing all the values.

What will be the output of the above code?

It’ll print something like that. You can see that all values are printing. This is what closure looks like.


          outerArg = 123 
          innerArg = 456 
          outerVar = a 
          innerVar = b 
          globalVar = xyz

        

As I already said, closure is nothing but a pretty simple topic.

Definition

Now let me tell you it's the perfect definition so closure is an inner function that has access to the variables in the outer (enclosing) function’s scope chain. Closure has access to variables in three scopes; specifically:

let me repeat it once again. Closure is an inner function which is innerFunc in our case has access to the variables in the outer (enclosing) function’s scope chain which is outerVar and globalVar.

Closure inside FOR loop

Let’s take one example for better understanding. What will be the output of the following code:


          for (var i = 0; i < 5; i++) {  
            setTimeout(function() { console.log(i); }, i * 1000 ); 
          }

        

After brainstorming, you’ll say that it’ll print 0,1,2,3,4. But you’re wrong. rather, it will display 5, 5, 5, 5, and 5.

reason for this is that each function executed within the loop will be executed after the entire loop has completed and all will therefore reference the last value stored in i, which was 5.

Closure in Action

This is where Closures comes into the picture. Closures can be used to prevent this problem by creating a unique scope for each iteration, storing each unique value of the variable within its scope, as follows:


          for (var i = 0; i < 5; i++) {     
            (function(x) {         
                setTimeout(function() { console.log(x); }, x * 1000 );              
            })(i); 
          }

        

This will produce the presumably desired result of logging 0, 1, 2, 3, and 4 to the console.

You can check my video on closure here for a better understanding.

Conclusion

Closures are one of those concepts in JavaScript that are difficult to understand at first. But once you understand them, you realize that things could not have been any other way.