What does it mean global namespace would be polluted?

Javascript

Javascript Problem Overview


What does it mean global namespace would be polluted?

I don't really understand what global namespace getting polluted means.

Javascript Solutions


Solution 1 - Javascript

Quick Note On 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.

Here is an example:

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

Adding this to your global namespace (at least for me) should ad 10,000 kb of memory usage (win7 firefox) which will not be collected. Other browsers may handle this differently.

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

Will allow arra to lose scope after the closure executes and be eligible for garbage collection.

Global Namespace Is Your Friend

Despite the many claims against using the global namespace, it is your friend. And like a good friend, you should not abuse your relationship.

Be Gentle

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

This is going to create 11 global variables which could possibly be overwritten or misconstrued somewhere.

Be Resourceful

A more resourceful approach, which does not pollute the global namespace, would be to wrap this all in the module pattern and only use one global variable while exposing multiple variables.

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

Solution 2 - Javascript

In JavaScript, declarations outside of a function are in the global scope. Consider this small example:

var x = 10;
function example() {
    console.log(x);
}
example(); //Will print 10

In the example above, x is declared in the global scope. Any child scope, such as that created by the example function, effectively inherit things declared in any parent scopes (in this case, that's just the global scope).

Any child scope that redeclares a variable declared in the global scope will shadow the global variable, potentially causing unwanted, hard to track bugs:

var x = 10;
function example() {
    var x = 20;
    console.log(x); //Prints 20
}
example();
console.log(x); //Prints 10

Global variables are usually not recommended because of the potential to cause problems like this. If we didn't use the var statement inside the example function, we would have accidentally overwritten the value of x in the global scope:

var x = 10;
function example() {
    x = 20; //Oops, no var statement
    console.log(x); //Prints 20
}
example();
console.log(x); //Prints 20... oh dear

If you want to read more and understand it properly, I suggest going through the ECMAScript specification. It may not be the most exciting of reads but it will help no end.

Solution 3 - Javascript

When you declare global variables, functions, etc., they, ehm, go to the global namespace. Aside from performance/memory issues (which may arise), you're likely to run into unfortunate name clashing, when you'll redefine an important variable or use not the value you think you use.

Defining things in the global namespace is to be avoided.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontheJavaView Question on Stackoverflow
Solution 1 - JavascriptTravis JView Answer on Stackoverflow
Solution 2 - JavascriptJames AllardiceView Answer on Stackoverflow
Solution 3 - JavascriptSergio TulentsevView Answer on Stackoverflow