JavaScript execution context

JavaScript Closures

why closures ?

All understandings of function execution stack, firstclass function, execution context won't be completed without understaing of closure. 

This is one of the most confusing but important topic one needs to understand, if he or she wants to master in javascript.

during closure even though function completes it's execution, it's memoryspace so as all it's variables are still available for all it's inner functions.

let's discuss it through a code analysis

function helloWorld(name) { return function bye(title){ console.log(title +' '+ name); } }

As you can see the function helloWorld returns another function. But notice it is returning the function as a whole. That means it is not invoking the returned function, just returning it as an executable chunk of code.

let's call the function helloWorld 

function helloWorld(name) { return function bye(title){ console.log(title +' '+ name); } } var hello = helloWorld('Tony'); hello('Mr.');

So here we are simply calling the function and assigning whatever the function is returning to a variable. In this case function helloWorld returning a function named bye which is getting assigned to a variable named as hello .Now note variable hello is containing a valid function in it. So what we do to call a function. 

Yes, we invoke it by the help of a pair of parenthesis '()' . In our case we are calling the funciton which is assigned to the variable hello by putting a pair of parenthesis and passing an argument Mr. [Please note the returned function bye takes one input parameter.]

Mr. Tony

why it's so?  How variable name still available for the function bye ?

Let us see what exactly happened here. We called a function and got something returned. So that called function's execution context is no more in the execution stack. As the function finished it got poped up from the execution context.

So the question remains who is retaning the value of the variable for future use. How the name name still avaiable for the hello function ?

Cinque Terre

If you see at the fig-a we could see the execution context of function helloWorld() with it's memory space which is holding value 'Tony' referred by name .  Now after the line var hello = hellowWorld('Tony'); the function execution is done and it returned another function; context got removed by the javascript engine . However it' s memory space is not.

So, when we are calling hello('Mr.')  we are creating execution context of the function hello() as shown by fig-b.  And the variable which as created by it's container function(i,e helloWorld) still avaiable for use. 

This phenomenon is called closures.

Back Next