What is Closure in Javascript?

What is Closure in Javascript?

ยท

1 min read

Simple definition for closure in javascript will be inner function having access to its outer function scope. Let's try to understand this with a simple example.

function showDetails(){
    var name = "Tenzinwoz";
    function showName(){
       console.log(name)
    }
    showName();
}
ShowDetails();
//Output : Tenzinwoz

As you can see that the inner function showName can access the outer function showDetails scope with variable name, that is closure in nutshell.

Let's go deeper with javascript closure by taking another example:

function showDetails() {
    var name = 'Tenzinwoz';
    function showName() {
      console.log(name);
    }
   return showName;
}

var myFunc = showDetails();
myFunc();
//Output: Tenzinwoz

I am sure you must be wondering how did myFunc() get access to outer function showDetails() variable as we return the entire function when we called the showDetails(). This is happening because of javascript closure when we create a function we also create a closure with its surrounding lexical scope.

ย