What is closure in Javascript and what is its use?

0
193
views
Understanding Closures in Javascript
Understanding Closures in Javascript

Understanding Javascript Closures

Javascript Closures: A Closure is something that Javascript does by default, it is a feature of the Javascript language that allows the language to have access to the proper variables, the variables it needs to execute the code written.

In this post, we will write several examples of Closures in Javascript, then we will dig into these examples, and show you what’s happening deeply in each.

Here’s our first example:

To begin with, We are going to write a function called `greet’.

 function greet(whattosay) {		
 }	

But instead of doing the work within this function, we are going to return a second function, within this greet function:
Using a function expression.

 function greet(whattosay) {		
   return function(name) {		
      console.log(whattosay + ', ' + name);		
   }		
 }		

Take a good look at what is going on here. The above function has done nothing but return the function nested within it. When greet is invoked, we will get that function value back, a value that we can invoke yet again.

Here is the above code in action:

 // Invoking the parent function and it's enclosed function:		
 
 greet('hi')('Dude');

 //=> 'Hi, Dude'

Something very interesting is happening here. To understand just how unusual the above code can be, lets write it a different way:


// Assigning the parent function to a variable
var hiDude = greet('hi');

// now heyDude is my function
hiDude('dude')

//=> "Hi, dude"

The above code is worth pondering. How does the hiDude function still recognize that there is a function within it that has yet to be called?

After all, the function has now run, and has been popped off the Execution Etack.

Nevertheless, this code runs just fine, as we have seen

That was a nice example. But what’s really going on here? How does Javascript know to return Hi Dude, when only
Dude is passed into the function? That’s the power of Closures. Lets demystify this and dig into what’s going on:

Lets review our code up to this point:

function greet(whattosay) {
  return function(name) {
     console.log(whattosay + ', ' + name);
  }
}

var hiDude = greet('hi');

hiDude('dude')

Introducing Execution Contexts

When a Javascript program runs, A global Execution Context is created. This global execution context, indicated by the
funny little box below, can be considered the first block in a stack that Javascript will create.

In the Global Execution Context, Javascript reads through the code, line by line loading all functions and global variables into memory.


 Global Execution Context   
 functions: `greet`         ---

When the first line of code var hiDude = greet('hi'); is hit, a new, Execution Context is created. That Execution Context
gets popped onto what is called the Execution Stack.

Remember what our greet function looks like:

function greet(whattosay) {
  return function(name) {
     console.log(whattosay + ', ' + name);
  }
}

Everything inside that function is popped onto a new Execution Stack, and the code is executed line by line.

Now, there are two Execution Contexts on the stack:


 Context: greet();  
 Variables: [whattosay: 'hi']
 Functions: function()
 ____________________________
 
 Context: global  
 Functions: `greet`         ---

The value of whattosay (hi) is loaded onto the Execution Context of the current function greet();

Now that we are in the Execution Context of greet(); Javascript continues to execute code line by line.
When the new function(); inside of greet is hit by the Javascript code, that function is then executed.

After that return, the greet(); function is “Popped” off the execution stack. It’s gone.

We said that each Execution Context has a space in memory, where all the variables and functions within it are stored. Under normal circumstances, a process called garbage collection would clear the data stored in memory away.

But at the moment that Execution Context finishes, the Execution Context is still there, present with the variables and functions defined within that context.

Now that the greet(); Execution Context has been popped off the execution stack, we are back to our global Execution Context.

Only this time, something is different, the variable ‘whattosay’ and it’s value, is remembered by the Javascript engine. They have not been cleared away by garbage collection:

Our Execution Context now looks something like this:


 Variables: [whattosay: 'hi'] (left behind, not garbage collected)
 _______________________
 Context: global  
 Functions: `greet`  ---

We now come to the next line in our javascript

  hiDude('dude')

Remember that this variable hiDude is actually a function, the return of the function that was originally inside greet();

When hiDude('dude') Is run, a new Execution Context for that function is popped onto the execution stack.

So now we have something like this:


 Context: hiDude;
 Variables: [name: 'dude']
 ________
 
 Variables: [whattosay: 'hi'] (left behind, not garbage collected)
 ________ 
 Context: global  
 Functions: `greet`  ---

What is happening here is critical to understand. A new execution context was created on top of the Global execution context.

Because this execution context was defined inside of the greet(); function, when it is created, it
ENCLOSES the variable from the parent function. That hanging variable that was never garbage collected.

That variable is ADDED to the variables known to that context, like so:


 Context: hiDude;
 Variables: [name: 'dude'], [whattosay: 'hi"]
 ______________
 
 Context: global  
 Functions: 'greet'  ---

The new function still has a reference to the variables created by its parent function. This process of enclosing that orphaned variable and including it in the new execution context is called a Closure.

A Closure is something that Javascript does by default, it is a feature of the Javascript language that allows the language to have access to the proper variables, the variables it needs to execute the code written.

I hope this clarifies the Javascript Closure. An incredibly important and interesting concept in Javascript.

LEAVE A REPLY

Please enter your comment!
Please enter your name here