DEV Community

Cover image for Demystifying [[environment]] in JavaScript Closure
Divakar Kumar
Divakar Kumar

Posted on • Updated on

Demystifying [[environment]] in JavaScript Closure

Hi all, For those who don't me I'm Divakar, Passionate developer with 5 years of experience in web and mobile development. I learned software development the hard way, following lots of confusing tutorials, failing to understand core concepts and finally having no idea how things work. So I wanted to help the community to
understand it in a better way without any hassle.

Before getting know about the closure i will start with couple of questions

Can you make a function to run only once ?

Can you make a function to memorize ?

By end of this article you will be able to answer those questions.


Every function in JavaScript is bound to have a [[ environment ]] or [[ scope ]] hidden property ,that have reference to the current lexical environment of their creation.

Do remember that lexical environment is theoretical and no one can get this object in console and manipulate it directly

Closure is a function that also have this hidden property along with it ,which stores the state of the current lexical environment, by which it can have access to outer variables. This makes closure in JavaScript as one of the most powerful concept.

Usually, a lexical environment gets removed from memory along with all the variables after the function calls finishes . But this is not the case in CLOSURE, it gets tied to the memory even after the function call finishes.

From now on i will be calling this hidden [[ scope ]] or [[ environment ]] property as a backpack.

In the above function , when getCounter() function call gets executed it runs in the execution context ,

Step 1: It searches for counter variable in the local memory of the execution context

Step 2: JS Engine cannot find the counter variable in the local memory of the execution context, now it looks into the backpack - Voila ! we found the counter variable and it picks up

Step 3: It increments the counter and the value gets modified in the backpack ( persistent memory ) as well. So if the getCounter() is called again , then the counter variable value will be incremented to one.

In the above code you could see that each time you initalize a variable with makeNewCounter , there will be independent backpacks available to getCounter and anotherCounter.

Great ! ๐ŸŽ‰๐ŸŽ‰ Now the next time you use closure , you have clear idea what is happening behind the scenes.

Since now you know about the closure and its actual working behind the scenes try to answer my first 2 questions

Can you make a function to run only once ?

Can you make a function to memorize ?

Top comments (0)