Practical Uses for Closures in Javascript?



In JavaScript, the closure is an environment which helps us to access an outer function’s scope from an inner function. In JavaScript, when a function is created, the closure also created. In other words, we can say closure is a way which allows functions that is present inside outer functions to access the outer function’s scope. In this article we are focusing on some practical uses of Closures in JavaScript.

Syntax

function outerFunction(){
   <initialize property>
   function updateProperty(){
      <update previously initialized property>
   }
   return updateProperty()
}

The syntax is straightforward. Closure only works for nested functions. The outer function will carry other variables and properties which will be updated by inner functions. Please note, these variables are not like global variables, they are specially belongs to the outer function body.

Use of Closure in JavaScript

Consider a simple case, where we are trying to implement a counter application. So when user does something, the counter will increase one by one. We can implement this by a function as follows−

let activity_counter = 0; //a global variable function new_activity() { // function to update the counter value activity_counter++; }

In the above example, a global variable activity_counter is initialized by 0, and a function is created to increase the activity counter value by one. This could be a solution but the main problem is, the global counter variable. This global variable can be changed by other users or scripts. That is not desired in our application.

We can implement this using closure to overcome this problem. In the following code snippet, an outer function: activityCounterClosure() initially creating a function called new_activity() which increases the counter and it is returning from the outer function. The beauty of this code is that, now the acc object is storing the function to increase the counter and as the counter variable is not global, it cannot be accessible from others.

function activityCounterClosure() { //outer function to implement closure let activity_counter = 0; //property which will be updated through the returned functions function new_activity() { activity_counter++; } return new_activity; } let acc = activityCounterClosure(); acc();

Example

The above code can be modified a little like the below −

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3>Output Console</h3> <p>Output:</p> <div id="output"></div> <div id="opError" style="color : #ff0000"></div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { function activityCounterClosure() { //outer function to create the closure let activity_counter = 0; function new_activity() { //function to increase the counter value activity_counter++; } function getCurrentCount() { //function to get current counter value return activity_counter; } return { new_activity: new_activity, getCurrentCount: getCurrentCount, }; } let { new_activity, getCurrentCount } = activityCounterClosure(); new_activity(); content += "Current Count value: " + JSON.stringify(getCurrentCount()) + '<br>'new_activity(); content += "Current Count value (next call): " + JSON.stringify(getCurrentCount()) + '<br>' } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

The outer function is returning two functions one for increasing the counter and another to get the current count value.

Use of Closure in JavaScript with HTML

Here we will see another example, where a new html block will be created by clicking on a button. The html content will be created with the help of closure property in JavaScript. Let us see the following example−

Example

<!DOCTYPE html> <html> <title>Online Javascript Editor</title> <head> </head> <body> <button onclick=addline()>Add a new line</button> </body> <script> function activityCounterClosure() { let activity_counter = 0; function new_activity() { activity_counter++; } function getCurrentCount() { return activity_counter; } return { new_activity : new_activity, getCurrentCount : getCurrentCount, }; } let {new_activity, getCurrentCount} = activityCounterClosure(); function createElement(startTag, endTag) { //return function which adds start and end part of an html document return function (innerHtml) { return `${startTag} ${innerHtml} ${endTag}`; }; } function addline() { // create div block, inside that insert paragraph with current button click value attached with it. new_activity(); var para = document.createElement('div') var blockEl = createElement('<p>', '</p>'); var block = blockEl("Current counter value:" + getCurrentCount()); para.innerHTML = block; document.body.appendChild(para); } </script> </html>

In this example, there are two closure functions. One is to increase the count and another for creating html component by adding inside text between paragraph tags. We are calling these functions after button click. So, when the button is clicked, a new line is generated inside the paragraph (<p>) tags.

Conclusion

In Javascript, closure is a very interesting as well as important concept. Closures gives access of outer function scope directly from inner functions. There are many applications. In this article two parallel scenario one is only based on pure JavaScript and another with HTML and JavaScript. One advantage of using closure is that, it does not like the global variable declaration so that the real value cannot be changed from other blocks.


Advertisements