JavaScript closures was a confusing topic to learn about today. It is a powerful feature embedded in the JavaScript engine. It’s confusing because even after a function is popped off the execution stack variables are recycled. Its most powerful feature is that you are able to make function factories. A factory is a function that returns or makes other things for us like another function.

After creating a function that returns another function, other things are in the global execution context. Things like a variable equaling another function to invoke the function factory. Then another function invokes the newly made variable equalling a returned value within the function first created.

How it works is that the global execution context runs, then executes the global variable equal to a function first. The global execution context returns a value found in the first created function. After it returns a value it’s stored in the variable memory and the execution time ends. However, the memory space for that global execution context still hangs around. Even after another line of a variable equaling a function a new execution context is created. This is what is important because each and every time a function is called a new execution context is created. Then after that second variable function is returned its value is also in memory hanging around after the function is popped off the execution stack.

After running a variable function underneath is usually a function that calls for a function that was returned. It will create a new execution context that will look in the outside environment reference. The JavaScript engine knows that the first one was created during the first execution context and points to that one. The one where it was created inside of the execution context returned it. Using the memory space hanging around after being executed forms a closure with the newly invoked function.

Again the main take away is that every time a function is called it gets its own execution context and any functions created inside of it will point to that execution context. It is pointing to the memory space as if the other executions didn’t disappear. It knows which ones to point to properly, where and when the execution properties were created.

This is very powerful because you can have a core set of logic and make functions that are easier to use. It allows you to create new functions that have some parameters by default by using closures.

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: