How to preserve variables in a JavaScript closure function?

JavascriptWeb DevelopmentFront End Technology

In this tutorial, we will look at the method to preserve variables in a JavaScript closure function.

What is a closure function? A closure function gives access to the scope of an outer function from an inner function. It also allows private variables. Closure variables are stored in stack and heap.

When a function is created, closure is also created. Closure remembers external things used in it. Closures are the primary mechanism for data privacy.

One drawback is that the variables used are not garbage collected. Overuse of closure functions will damage the system due to redundant code in memory.

Let’s briefly introduce the method to preserve a variable in a closure function.

Using the Closure Return Function

We must preserve the JavaScript closure variable when it reinitializes for each call to the function. The solution is not to set the object to empty whenever the function is called.

Syntax

Users can follow the syntax below for using the closure function.

var closureFunction = function(param) {
   var object = {};
   return function(param) {
      object[param] = param;
      return object;
   }
}();
closureFunction(value1);
closureFunction(value2);

Here, the syntax describes a closure function that returns an object.

Parameters

  • param − The argument to the closure function.

Example

Let us understand the need for a closure return function in this example.

In this program, we are calling retClosProb(10) first. The object retClosProbs is set to empty in this function. Then the value is assigned to the object, and the object is returned for display.

Note that all the actions are done outside the return function in this program. Since the object is reinitialized for every call to the function, we get the object value separately every time. That is, the object is not preserved.

<html> <html> <title>The JavaScript program to see a variable that is not preserved</title> </html> <body> <div id="retClosBtnWrap"> <p>Click this button to see the object that is not preserved</p> <button onclick="retClosAction()"> Click Me</button> </div> <p id="retClosOp1"></p> <p id="retClosOp2"></p> <script> var retClosOutEl1 = document.getElementById("retClosOp1"); var retClosOutEl2 = document.getElementById("retClosOp2"); var retClosBtnWrapEl = document.getElementById("retClosBtnWrap"); function retClosAction() { retClosBtnWrapEl.style.display = "none"; var retClosProb = function(id) { retClosProbs = {}; retClosProbs[id] = "Value " + id; return retClosProbs; return function() {} }; retClosOutEl1.innerHTML = JSON.stringify(retClosProb(10)); retClosOutEl2.innerHTML = JSON.stringify(retClosProb(20)); } </script> </body> </html>

Example

In this example, let us understand the solution to the problem said in the above example.

We are calling retClosSoln(10) first. In this function, the object retClosSoln is declared inside the function.

Next comes the difference when compared to the problem example given above. The value is assigned to the object, and the object is returned for display inside the return function.

Since the object is not reinitialized for every call to the function, we get the object values together. That is, the object is preserved.

<html> <body> <div id="retClosBtnWrap"> <p>Click this button to see the object that is preserved</p> <button onclick="retClosAction()"> Click Me</button> </div> <p id="retClosOp1"></p> <p id="retClosOp2"></p> <script> var retClosOutEl1 = document.getElementById("retClosOp1"); var retClosOutEl2 = document.getElementById("retClosOp2"); var retClosBtnWrapEl = document.getElementById("retClosBtnWrap"); function retClosAction() { retClosBtnWrapEl.style.display = "none"; var retClosSolns = function(id) { var retClosSoln = {}; return function(id) { retClosSoln[id] = "Value " + id; return retClosSoln; } }(); retClosOutEl1.innerHTML = JSON.stringify(retClosSolns(10)); retClosOutEl2.innerHTML = JSON.stringify(retClosSolns(20)); } </script> </body> </html>

Example

In this example, we have done the same closure return function solution to preserve a variable that we just discussed in the example above. The only difference in this program is that we are getting the values to the closure variable from the user.

<html> <body> <input type="text" id="retClosUsrInp1" placeholder="Enter name" /> <br><br> <input type="text" id="retClosUsrInp2" placeholder="Enter name" /> <div id="retClosUsrBtnWrap"> <p id="retClosUsrErr" style="color:red;font-weight:bold"></p> <p>Click this button to see the preserved values</p> <button onclick="retClosUsrAction()"> Click Me</button> </div> <p id="retClosUsrOp1"></p> <p id="retClosUsrOp2"></p> <script> var retClosUsrOutEl1 = document.getElementById("retClosUsrOp1"); var retClosUsrOutEl2 = document.getElementById("retClosUsrOp2"); var retClosUsrErrEl = document.getElementById("retClosUsrErr"); var retClosUsrBtnWrapEl = document.getElementById("retClosUsrBtnWrap"); function retClosUsrAction() { var retClosUsrVal1 = document.getElementById("retClosUsrInp1").value; var retClosUsrVal2 = document.getElementById("retClosUsrInp2").value; if (retClosUsrVal1 == "" || retClosUsrVal2 == "") { retClosUsrErr.innerHTML = "Please provide inputs and click on the button"; } else { retClosUsrBtnWrapEl.style.display = "none"; var retClosUsrSolns = function(id) { var retClosUsrSoln = {}; return function(id) { retClosUsrSoln[id] = "Hello " + id; return retClosUsrSoln; } }(); retClosUsrOutEl1.innerHTML = JSON.stringify(retClosUsrSolns(retClosUsrVal1)); retClosUsrOutEl2.innerHTML = JSON.stringify(retClosUsrSolns(retClosUsrVal2)); } } </script> </body> </html>

In this tutorial, we discussed how to preserve a variable in JavaScript closure functions.

We have analyzed the problem case and found a solution by using the return function in closure. In brief, closures provide data encapsulation. With the help of closures, we can remove redundant code.

raja
Updated on 20-Oct-2022 07:34:57

Advertisements