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 prevent overriding using Immediately Invoked Function Expression in JavaScript?
JavaScript allows developers to add functionality and behaviors to the web page. Developers require to create multiple functions and variables to add functionality to different parts of the web page.
While developing real-time applications, multiple developers work on the same project. So, avoiding the unintentional overriding of functions and variables while collaborating with multiple developers is necessary. In this tutorial, we will learn to prevent overriding using immediately invoked function expressions.
Problem of Overriding
For example, two colleagues are working on the same project, and both have defined the printAge() function inside the code and merged the code. Now, the browser will execute only the function which is defined at last, as it overrides all other function definitions with the same name. So, users can sometimes see the unexpected behaviour of web pages. Also, it can happen with variable names.
Example (Overriding Problem)
In the example below, we defined two variables with the same name. We show the variable value on the web page. In the output, users can observe that the second 'a' variable overrides the value of the first 'a' variable.
<html>
<body>
<h2> Visualizing the overriding in JavaScript </h2>
<div id="output"></div>
<script>
let output = document.getElementById('output');
var a = "Hello World!";
var a = "Hi World!"; // This overrides the first declaration
output.innerHTML = "The value of a is " + a;
</script>
</body>
</html>
The value of a is Hi World!
The Solution to Prevent Overriding Using IIFE
JavaScript function has functional scope for the variables defined inside the function. So, whatever variables we define inside the function, we can't access them outside the function. We can use Immediately Invoked Function Expressions (IIFE) to create isolated scopes and prevent variable overriding.
IIFE executes instantly after defining the function. We don't require to define a function name, and variables inside remain private to that function scope.
Syntax
Users can follow the syntax below to use IIFE to prevent overriding in JavaScript.
(function () {
// write JavaScript code here.
})();
In the above syntax, we added the function expression inside parentheses. The second set of parentheses immediately invokes the function.
Example (Preventing Overriding Using IIFE)
In the example below, we defined two immediately invoked functions. In each function, we create an 'obj' object variable and store the id, user, and age properties. Also, we store the printAge() function in the object.
The printAge() function of both objects prints different messages. After that, we stored both objects in the window object to access them globally. In the end, we executed the printAge() method of both objects.
<html>
<body>
<h3>Preventing the overriding <i>using the Immediately Invoked Function Expression</i> in JavaScript</h3>
<div id="output"></div>
<script>
let output = document.getElementById("output");
// First IIFE - creates user1 object
(function (window) {
var obj = {};
obj.id = "123";
obj.user = "Shubham";
var age = "Shubham's Age is 23. <br>";
obj.printAge = function () {
output.innerHTML += age;
}
window.user1 = obj;
})(window);
// Second IIFE - creates user2 object
(function (window) {
var obj = {};
obj.id = "342";
obj.user = "Mukund";
var age = "Mukund's Age is 18. <br>";
obj.printAge = function () {
output.innerHTML += age;
}
window.user2 = obj;
})(window);
user1.printAge();
user2.printAge();
</script>
</body>
</html>
Shubham's Age is 23. Mukund's Age is 18.
Example (Multiple Objects with Same Method Names)
In this example, we have defined two immediately invoked function expressions. Both define setId() and setName() methods without overriding each other because they exist in separate scopes.
<html>
<body>
<h3>Preventing the overriding <i>using the Immediately Invoked Function Expression</i> in JavaScript</h3>
<div id="output"></div>
<script>
let output = document.getElementById("output");
// First IIFE - preparing food data
(function (window) {
var food = {};
var setId = function () {
return Date.now();
}
var setName = function () {
return "Apple";
}
window.food = {
setId: setId(),
setName: setName()
};
})(window);
// Second IIFE - preparing watch data
(function (window) {
var watch = {};
var setId = function () {
return Date.now();
}
var setName = function () {
return "Titan";
}
window.watch = {
setId: setId(),
setName: setName()
};
})(window);
// printing values of objects
output.innerHTML = "Food Id: " + food.setId + "<br/>" +
"Food Name: " + food.setName + "<br/>" +
"Watch Id: " + watch.setId + "<br/>" +
"Watch Name: " + watch.setName;
</script>
</body>
</html>
Food Id: 1704123456789 Food Name: Apple Watch Id: 1704123456790 Watch Name: Titan
Benefits of Using IIFE
The main benefits of preventing overriding using IIFE are:
- Avoiding Global Pollution: Variables remain in local scope
- Code Maintainability: Each module is self-contained
- Collision Prevention: Same variable names can exist in different IIFEs
- Immediate Execution: Code runs instantly without explicit function calls
Conclusion
IIFE provides an elegant solution to prevent variable and function overriding in JavaScript. By creating isolated scopes, multiple developers can work on the same project without worrying about naming conflicts. This pattern is fundamental in modern JavaScript development and module systems.
