DEV Community

Cover image for Closures in javascript (πŸ”–)
Aishanii
Aishanii

Posted on

Closures in javascript (πŸ”–)

This is a very easy topic and quite important too. A lot of output questions are framed out of this one.

So a closure is nothing but function + it's outside environment.

Let's take an example to break this statement down:

function hi(){
   var k="I am great!"

    function reply(){
        console.log(k);
    }

    k="Long time no see"
    reply();
    return reply;

}
var ans=hi();
console.log(ans)
Enter fullscreen mode Exit fullscreen mode

In this case function reply() forms a closure with it's surrounding, function hi() in this case. So, when trying to access k inside, it gets the value. Moreover, as you can see we update value of k, which the reply function pick ups too.

Image description

Once returned, the reply() still holds on to it's environment throughout the execution. This is because it returns a closure.

As mentioned in the last blog, this explains the lexical scope. A function can not only access it's parent scope but also it's parent's parent scope and so on. This access is also valid outside the lexical function.

If you are a react developer, it is a very common question when someone asks if states are synchronous. Would recommend to go through this!
⭐Async and setState

Top comments (0)