What is global namespace pollution in JavaScript?


Global namespace pollution

Polluting Global namespace causes name collision. This name collision is very common in large projects where we may be using several javascript libraries. Let's discuss in detail what a name collision is.

let's take a scenario in which 2 teams named A1 and A2 are working on a project. They both prepared their own javascript files that is TeamA1.js and TeamA2.js as shown below.

TeamA1.js

TeamA1 has created a student function and has 2 parameters fname and lname(firstname & lastname).

function student(fname, lname){
   this.fname = fname;
   this.lname = lname;
   this.getFullName = function (){
      return this.fname + " " + this.lname
   }
}

TeamA2.js

TeamA2 has created the same function(student) and has 3 parameters fname, mname, lname.

function student(fname, mname, lname){
   this.fname = fname;
   this.mname = mname;
   this.lname = lname;
   this.getFullName = function (){
      return this.fname + " " + this.mname + " " + this.lname;
}
}

Now create an html file to operate the above js files. Place the js files in <head> tag

Html file

<html>
<head>
<script type = "javascript" src = "TeamA1.js"></script>
<script type = "javascript" src = "TeamA2.js"></script>
</head>
<body>
<div id = "resultDiv"></div>
<script>
   document.getElementById("resultDiv").innerHTML =
   new student("Rajendra", "prasad").getFullName();
</script>
</body>
</html>

If we run the code the following output will be displayed.

Output

Rajendra prasad undefined

Explanation

We have here two student functions one is with 2 parameters and other is with 3 parameters. Our aim is to use student function with 2 parameters, so in the html file only two parameters("Rajendra", "prasad")  have passed. But the output we got is "Rajendra prasad undefined", which means the code had taken a function with 3 parameters rather than function with 2 parameters. 

The reason behind this is javascript won't encourage function overloading. It just overrides the function with another function having the same name(Here it is student). In our example since function with 3 parameters(TeamA2.js) has placed after function with 2 parameters(TeamA1.js), TeamA2 function overridden the TeamA1 function, displaying undefined in the output. In case if the places of two js files have reversed their respective places then the output will be "Rajendra prasad". 

Here we can say that name collision has happened. Both the teams have constructed a function with the same name that is student. That's why it is very important not to add everything to the global namespace. If someone else use the same variable or function names, it can lead to name collision.

raja
Published on 19-Jun-2019 13:21:56
Advertisements