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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay