Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to preserve variables in a JavaScript closure function?
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.
The Problem: Variables Not Preserved
When a variable is reinitialized inside a function on every call, previous values are lost. This happens when the variable declaration is placed in the wrong scope.
<html>
<body>
<div id="problemDemo">
<p>Click this button to see the object that is not preserved</p>
<button onclick="showProblem()">Click Me</button>
</div>
<p id="output1"></p>
<p id="output2"></p>
<script>
function showProblem() {
document.getElementById("problemDemo").style.display = "none";
var problematicFunction = function(id) {
var storage = {}; // Reinitialized on every call
storage[id] = "Value " + id;
return storage;
};
document.getElementById("output1").innerHTML = JSON.stringify(problematicFunction(10));
document.getElementById("output2").innerHTML = JSON.stringify(problematicFunction(20));
}
</script>
</body>
</html>
{"10":"Value 10"}
{"20":"Value 20"}
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
var closureFunction = function() {
var object = {};
return function(param) {
object[param] = param;
return object;
}
}();
closureFunction(value1);
closureFunction(value2);
Parameters
param ? The argument to the closure function.
Example: Preserved Variables Solution
In this example, the object is declared in the outer function scope and preserved across multiple calls to the inner function.
<html>
<body>
<div id="solutionDemo">
<p>Click this button to see the object that is preserved</p>
<button onclick="showSolution()">Click Me</button>
</div>
<p id="result1"></p>
<p id="result2"></p>
<script>
function showSolution() {
document.getElementById("solutionDemo").style.display = "none";
var preservedFunction = function() {
var storage = {}; // Declared once in outer scope
return function(id) {
storage[id] = "Value " + id;
return storage;
}
}();
document.getElementById("result1").innerHTML = JSON.stringify(preservedFunction(10));
document.getElementById("result2").innerHTML = JSON.stringify(preservedFunction(20));
}
</script>
</body>
</html>
{"10":"Value 10"}
{"10":"Value 10","20":"Value 20"}
Example: User Input with Preserved Values
This example demonstrates the same closure concept but accepts user input values instead of hardcoded ones.
<html>
<body>
<input type="text" id="userInput1" placeholder="Enter name" />
<br><br>
<input type="text" id="userInput2" placeholder="Enter name" />
<div id="userDemo">
<p id="errorMsg" style="color:red;font-weight:bold"></p>
<p>Click this button to see the preserved values</p>
<button onclick="handleUserInput()">Click Me</button>
</div>
<p id="userResult1"></p>
<p id="userResult2"></p>
<script>
function handleUserInput() {
var val1 = document.getElementById("userInput1").value;
var val2 = document.getElementById("userInput2").value;
if (val1 == "" || val2 == "") {
document.getElementById("errorMsg").innerHTML = "Please provide inputs and click on the button";
} else {
document.getElementById("userDemo").style.display = "none";
var userClosure = function() {
var userStorage = {};
return function(id) {
userStorage[id] = "Hello " + id;
return userStorage;
}
}();
document.getElementById("userResult1").innerHTML = JSON.stringify(userClosure(val1));
document.getElementById("userResult2").innerHTML = JSON.stringify(userClosure(val2));
}
}
</script>
</body>
</html>
How It Works
The key difference lies in variable placement:
- Problem: Variable declared inside the inner function gets reinitialized on every call
- Solution: Variable declared in outer function scope persists between inner function calls
Conclusion
To preserve variables in JavaScript closures, declare them in the outer function scope rather than the inner function. This technique enables data persistence across multiple function calls while maintaining encapsulation.
