Understanding "Closures" and Lexical Environment

Couldn't understand closures? Let's clear this.

ยท

2 min read

Understanding "Closures" and Lexical Environment

What is Closure ??

Heard someone saying "this piece of code is possible because of closure" ?!

Most probably you encountered this word somewhere in your coding journey.
One of the core concepts that every JS developer should know.

Well, what is closure anyway?

Here is the definition:

Functions along with its lexical environment(surrounding state) are called Closures

oh wow wait wait.... what is lexical environment??
There is no going further without knowing this one.

Lexical environment is the local memory plus the lexical environment of the parent

...That ain't helping! I know.

So whenever an execution context is created a lexical environment is also created internally.
Say for a function, this lexical environment has all the values of that function(local memory) plus a reference to its parent.

If all these terminologies like execution context, seems confusing, I suggest you read the below blog-
How JavaScript works ๐Ÿ‘ˆ It has more than 1K views.

Le's see an example:

function a() {
    var num = 10;
    function b() {
        var newNum = num + 5;
        console.log(newNum)
    }
}

Here we can say that function b is sitting lexically inside function a.

So, lexical environment of function b is the local memory of b (which has those two lines of b) plus the lexical environment of function a(which has var num).

Okay, so what is the lexical environment of function a? Local memory of that function with a reference(lexical environment) to its parent, which is the global memory.

Now you got what is Lexical Environment ( I guess...if confused, drop in comments )

Okay, that was something, but hey, what's closure?
Yo, please don't give me another big explanation!

This itself is Closure!! In JavaScript, functions form closures. Hence the inner functions can access variables that are outside the function.
[updated on 30/7/21]

That's it for now :) Let's catchup on twitter

Did you find this article valuable?

Support Mansoor Ameen's Blog by becoming a sponsor. Any amount is appreciated!

ย