DEV Community

Vijay SRJ
Vijay SRJ

Posted on • Originally published at fullstackdeveloper.guru

What is a closure in Javascript?

Let’s say you declare a variable in javascript.

What is the scope of this variable?

It is the entire function in which it is declared.

What if it is declared within a particular block ?

Still it’s scope is the entire function in which it is declared.

For example:

function test(value){

     if(value==1){
             var temp = "Hello the value entered is 1";

          }
        alert(temp);       //you can access temp here!
}
Enter fullscreen mode Exit fullscreen mode

In the above code even though the variable temp is declared inside the if block , the scope of the variable is the entire function test() , hence the alert statement will alert the value “Hello the value entered is 1” .

But , this will work only if the value is 1 , if the value does not match , javascript will skip the initialization of the variable and you will get undefined for the variable ‘temp’.

Let’s play a little more with scope of a variable.

Now , lets say the above function returns another function which accesses the variable “value”:

function test(value){



    return function(){

        console.log(value);

        value++;

        return value;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now , does the returned function has access to the variable “value” once is it is returned.

Like when you assign the returned function like this:

var returnedfunction = test(5);
and then you call the returned function:

returnedfunction();
Does the returnedfunction() now has access to the variable “value”?

It does!

The value of the variable “value” is incremented every time you call returnedfunction().

I called it thrice in my code and it returned 5,6 and 7:

<script>

function test(value){



    return function(){

        console.log(value);

        value++;

        return value;
    }
}


var returnedfunction = test(5);

returnedfunction();

returnedfunction();

returnedfunction();


</script>
Enter fullscreen mode Exit fullscreen mode

The output was
5
6
7
This connection to the variable in its surrounding scope for the returned function + the returned function are together called a closure.

Repeating it again :

Closure = a function + its connection to variables in its surrounding scopes even after it leaves the scope where it was created

That’s it!

Top comments (0)