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!";
      output.innerHTML = "The value of a is " + a;
   </script>
</body>
</html>

The Solution to Prevent Overriding Using the Immediately Invoke Function

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. So, we can define variables with a scope limited to the function.

We can use the immediately invoked functions to solve the function overriding, which executes instantly after defining the function. So, we don’t require to define the function name, and we can prevent the overriding.

Syntax

Users can follow the syntax below to use the immediately invoke function to prevent the overriding in JavaScript.

(function () {
   // write JavaScript code here. 
})();

In the above syntax, we added the function expression inside the parenthesis. Also, we added parenthesis after the function definition to immediately invoke the function.

Example (Preventing the Overriding Using the Immediately Invoke Function)

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, and users can observe that it prints the original message without overriding each other.

<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");
      (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);
      (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>

Example

In this example also, we have defined two immediately invoked function expressions. In the first expression, we defined the food object. Also, we defined the setId() and setName() methods for the food object and stored it inside the window object.

In the second function expression, we again defined the setId() and setName() methods and stored them in the watch() object. After that, we access different methods by taking the watch and food object as a reference. In the output, we can see that it prints the original message without overriding it.

<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");
      (function (window) {
         // preparing food data
         var food = {};
         var setId = function () {
            return Date.now();
         }
         var setName = function () {
            return "Apple";
         }
         window.food = {
            setId: setId(),
            setName: setName()
         };
      })(window);
      (function (window) {
      
         // preparing watch data
         var watch = {};
         var setId = function () {
            return Date.now();
         }
         var setName = function () {
            return "Titan";
         }
         window.watch = {
            setId: setId(),
            setName: setName()
         };
      })(window);
      
      // printing values of object
      output.innerHTML = "Food Id: " + food.setId + "<br/>" + "Food Name: " + food.setName + "<br/>" + "Watch Id: " + watch.setId + "<br/>" + "Watch Name: " + watch.setName;
   </script>
</body>
</html>

We learned to use the immediately invoke function expression to prevent overriding while working with JavaScript code. The idea is to define the variables in the functional scope and access them globally via a particular global object, which should not have any overriding names.

The main benefit of preventing overriding using the immediately invoke function expression is avoiding global pollution of variable names. Also, it allows us to make code maintainable and increases the code reusability.

Updated on: 26-Jul-2023

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements