DEV Community

Cover image for Closures in javascript (🔖)
Aishanii
Aishanii

Posted on

1 1

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)