What does it mean global namespace would be polluted?

Asked
Active3 hr before
Viewed126 times

7 Answers

90%

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.,How to avoid namespace pollution in JavaScript?,What is a namespace in Python?

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
   }
}
load more v
88%

I don't really understand what global namespace getting polluted means. ,Don't abuse (usually referred to as "polluting") the global namespace. And what I mean by do not abuse the global namespace is - do not create multiple global variables. Here is a bad example of using the global namespace.,What does it mean global namespace would be polluted?,Defining things in the global namespace is to be avoided.

Here is an example:

var arra = [];
for (var i = 0; i < 2003000; i++) {
   arra.push(i * i + i);
}

Whereas having that same code in a scope which goes out of scope like this:

(function() {
   var arra = [];
   for (var i = 0; i < 2003000; i++) {
      arra.push(i * i + i);
   }
})();

Don't abuse (usually referred to as "polluting") the global namespace. And what I mean by do not abuse the global namespace is - do not create multiple global variables. Here is a bad example of using the global namespace.

var x1 = 5;
var x2 = 20;
var y1 = 3
var y2 = 16;

var rise = y2 - y1;
var run = x2 - x1;

var slope = rise / run;

var risesquared = rise * rise;
var runsquared = run * run;

var distancesquared = risesquared + runsquared;

var distance = Math.sqrt(dinstancesquared);

Here is an example: (Please note this is simple and there is no error handling)

//Calculate is the only exposed global variable
var Calculate = function() {
   //all defintions in this closure are local, and will not be exposed to the global namespace
   var Coordinates = []; //array for coordinates
   var Coordinate = function(xcoord, ycoord) { //definition for type Coordinate
      this.x = xcoord; //assign values similar to a constructor
      this.y = ycoord;
   };

   return { //these methods will be exposed through the Calculate object
      AddCoordinate: function(x, y) {
         Coordinates.push(new Coordinate(x, y)); //Add a new coordinate
      },

      Slope: function() { //Calculates slope and returns the value
         var c1 = Coordinates[0];
         var c2 = Coordinates[1];
         return c2.y - c1.y / c2.x - c1.x; //calculates rise over run and returns result
      },

      Distance: function() {
         //even with an excessive amount of variables declared, these are all still local
         var c1 = Coordinates[0];
         var c2 = Coordinates[1];

         var rise = c2.y - c1.y;
         var run = c2.x - c1.x;

         var risesquared = rise * rise;
         var runsquared = run * run;

         var distancesquared = risesquared + runsquared;

         var distance = Math.sqrt(distancesquared);

         return distance;
      }
   };
};

//this is a "self executing closure" and is used because these variables will be
//scoped to the function, and will not be available globally nor will they collide
//with any variable names in the global namespace
(function() {
   var calc = Calculate();
   calc.AddCoordinate(5, 20);
   calc.AddCoordinate(3, 16);
   console.log(calc.Slope());
   console.log(calc.Distance());
})();
load more v
72%

Polluting global namespace causes a name collision. It is especially true for large projects where we use several libraries and third-party libraries as well. So that’s why it is very important that not to add everything in the global namespace.,In this article we will understand what is Global Namespace Pollution is in JavaScript and How to overcome this problem in javascript.,Javascript lacks namespaces. But we can use the namespace to create objects below is the code for creating objects for namespace,In the above code, we have added a method that takes 2 and 3 parameters respectively which works perfectly fine.

In object-oriented programming languages like Java, C# we have the concept of function or method overloading. In which we can have the same method name but parameters are different. So such kind of code is work in that programming languages without any issue see below code

using System;
class abc { // adding two integer values.     public int Add(int a, int b)     {         int sum = a + b;         return sum;     }       // adding three integer values.     public int Add(int a, int b, int c)     {         int sum = a + b + c;         return sum;     }       // Main Method     public static void Main(String[] args)     {           // Creating Object         abc ob = new abc ();           int sum1 = ob.Add(1, 2);         Console.WriteLine("sum of the two "                          + "integer value : " + sum1);           int sum2 = ob.Add(1, 2, 3);         Console.WriteLine("sum of the three "                          + "integer value : " + sum2);     } }
load more v
65%

The above call to getCellID is currently being executed successfully. It means I have polluted the global namespace. I am going to fix it.,Here is the solution.,In the above case the call to showCalendar was successful. However call to getCallID failed. That's good. It means I am not polluting the global namespace.,My main concern is that as Javascript develeoper I should not be polluting global namespace. I could write the calendar code like this.

1 showCalendar = function(options, d) {};
2
3 calendarHeaderMonth = function(opts) {};
4
5 calendarHeaderWeek = function(opts) {};
6
7 calendarData = function(opts) {};
8
9 drawCalendar = function(opts, d) {};
10
11 getCellID = function(year, month, day) {};
12
13 // use showCalendar
14 showCalendar({}, new Date());
load more v
75%

I don't really understand what global namespace getting polluted means. ,Will allow arra to lose scope after the closure executes and be eligible for garbage collection. ,As variables lose scope, they will be eligible for garbage collection. If they are scoped globally, then they will not be eligible for collection until the global namespace loses scope.,What does it mean global namespace would be polluted?

Here is an example:

var arra = [];
for (var i = 0; i < 2003000; i++) {
   arra.push(i * i + i);
}

Whereas having that same code in a scope which goes out of scope like this:

(function() {
   var arra = [];
   for (var i = 0; i < 2003000; i++) {
      arra.push(i * i + i);
   }
})();

Don't abuse (usually referred to as "polluting") the global namespace. And what I mean by do not abuse the global namespace is - do not create multiple global variables. Here is a bad example of using the global namespace.

var x1 = 5;
var x2 = 20;
var y1 = 3
var y2 = 16;

var rise = y2 - y1;
var run = x2 - x1;

var slope = rise / run;

var risesquared = rise * rise;
var runsquared = run * run;

var distancesquared = risesquared + runsquared;

var distance = Math.sqrt(dinstancesquared);

Here is an example: (Please note this is simple and there is no error handling)

//Calculate is the only exposed global variable
var Calculate = function() {
   //all defintions in this closure are local, and will not be exposed to the global namespace
   var Coordinates = []; //array for coordinates
   var Coordinate = function(xcoord, ycoord) { //definition for type Coordinate
      this.x = xcoord; //assign values similar to a constructor
      this.y = ycoord;
   };

   return { //these methods will be exposed through the Calculate object
      AddCoordinate: function(x, y) {
         Coordinates.push(new Coordinate(x, y)); //Add a new coordinate
      },

      Slope: function() { //Calculates slope and returns the value
         var c1 = Coordinates[0];
         var c2 = Coordinates[1];
         return c2.y - c1.y / c2.x - c1.x; //calculates rise over run and returns result
      },

      Distance: function() {
         //even with an excessive amount of variables declared, these are all still local
         var c1 = Coordinates[0];
         var c2 = Coordinates[1];

         var rise = c2.y - c1.y;
         var run = c2.x - c1.x;

         var risesquared = rise * rise;
         var runsquared = run * run;

         var distancesquared = risesquared + runsquared;

         var distance = Math.sqrt(distancesquared);

         return distance;
      }
   };
};

//this is a "self executing closure" and is used because these variables will be
//scoped to the function, and will not be available globally nor will they collide
//with any variable names in the global namespace
(function() {
   var calc = Calculate();
   calc.AddCoordinate(5, 20);
   calc.AddCoordinate(3, 16);
   console.log(calc.Slope());
   console.log(calc.Distance());
})();
load more v
40%

In certain places, it is permitted to have a using declaration, which is of the form using ::foo::bar;,This is because: 1) it defeats the entire purpose of namespaces, which is to reduce name collision; 2) it makes available to the global namespace the entire namespace specified with the using directive.,Everywhere where using declaration only affects a limited and clearly visible portion of code it is perfectly acceptable.,By writing it this way, we avoid error-prone ADL along with using directives and declarations.

People like to put using directives in their code because it saves a lot of typing, but it comes with risk. If you have a file with a lot of cout statements, I can understand not wanting to have to type std::cout a hundred times, but you can simply say using ::std::cout. I treat these like variable declarations: scope them where they are needed. If one function in a file of 10 needs to write output, don't declare the cout way at the top, put it in that function that is doing the actual output.

#include <ostream>
//using namespace std; // NO!
//using ::std::cout;   // less bad than using namespace, but I prefer to scope it

int main(int argc, char** argv)
{
   int rc = do_some_stuff(argc, argv);
   using ::std::endl;
   if (rc) { // print the success report
      using ::std::cout;
      cout << "The test run completed. The return code was " << rc << '.' << endl;
    } else {
      using ::std::cerr;
      cerr << "Unable to complete the test run." << endl;
    }
    return 0 == rc;
}

Another thing one can do is alias or typedef to minimize the typing. I don't find std::whatever to be that bad, but we have a huge set of source with several dozen modules and sometimes we have to write code like console_gui::command_window::append("text"). That gets tedious after a while and causes a lot of long lines. I am all for something like

typedef console_gui::command_window cw;
cw::append("text");
load more v
22%

"As variables lose scope, they will be eligible for garbage collection. If they are scoped globally, then they will not be eligible for collection until the global namespace loses scope...",Imported names are "module global" but do not create properties on the global object,All definitions are scoped, so leaving the scope will delete the definitions, const and let are block scoped so they don't affect the global object.

var myRevealingModule = (function() {

   var privateVar = "Ben Cherry",
      publicVar = "Hey there!";

   function privateFunction() {
      console.log("Name:" + privateVar);
   }

   function publicSetName(strName) {
      privateVar = strName;
   }

   function publicGetName() {
      privateFunction();
   }

   // Reveal public pointers to
   // private functions and properties

   return {
      setName: publicSetName,
      greeting: publicVar,
      getName: publicGetName
   };

})();

myRevealingModule.setName("Paul Kinlan");
load more v

Other "undefined-undefined" queries related to "What does it mean global namespace would be polluted?"