On JavaScript Closures

A function that returns a child function in which child function still has access to the properties / declarations of the parent function, even after the execution of the parent function is usually referred to as a Closure. For example,

According to the above example, even after the execution of ‘square’ function, the returning child function has access to the value of ‘x’. Here under we examine how this is possible.

Like in many other languages limits the existence of a variable within a code block, JavaScript variables exist within a function block. For example,

Here we first prints the value of ‘result’ variable and then refer the value of ‘x’ variable to initialize the value of ‘result’ variable. But, under the hood of JavaScript engine it moves variable declarations to the top of the function block. Which is know as hoisting. This somewhat ensures the declaration of variables within a function block before those are used.

One the hoisting is done, previous code block would looks like above.

For each execution of a function block a data structure called Lexical Environment (environment) is created. Each environment is stacked based on the execution context and it holds the outer environment / environment of the parent’s execution context and references to the values declared in the current execution context.

If we consider the above example where we have ‘square’ function declared in the global scope in which that function returns an object containing a function called ‘calc’. The environment stack would looks like below,

Likewise, every execution context has it’s own environment where it holds references to the values of the properties. This is also referred to as scope. Since environment could trace it’s parent scope’s environment, it could access references of the parent scope’s properties. This lay down the foundation of the JavaScript Closures.

References:

Rock on!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s