What does it mean global namespace would be polluted?

What does it mean global namespace would be polluted?

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

better views of javascript polluted global namespace

Is there an easy way to see what variables you (or other libraries) have polluted to the global namespace? In the (chrome) debugger console, typing this/this.window reveals hundreds of objects, even w

“Controllers polluting the Global Namespace” what does it mean in Angular

I am newbie to Angular.js , i have read that Controllers should not pollute the global namespace. What does it really means and why angular.module(‘SomeApp’,[]).controller(‘SomeController’, function(

Is javascript namespace polluted?

I do not have a good grasp of the js namespace and am WAGing* re the title, but that’s one of my guesses about what’s happening. WAG = Wild Guess My app is crashing (dramatically); trying to figure

What does it mean when the function in global namespace is declared as static C++? [duplicate]

Possible Duplicate: What is a “static” function? I have seen a function in a global namespace that is declared like this: static int function_name(int a, double* p, int c, float * u) { //do somethin

STLPORT: What does namespace std{} mean?

In the stlport library, I saw this code: namespace std { } namespace __std_alias = std; 1. Are they trying to nullify the standard std namespace in the first line? 2. Why in the world would they use

What does “global variables are bad” mean?

So I can read from a global variable def f() : print x And I can also assign it def g() global x x = 3 When people say global variables are bad, do they mean that both reading and assigning are ba

What does $$ mean in PHP?

Example is a variable declaration within a function: global $$link; What does $$ mean?

What does only `namespace` mean in this situation?

Seeing this line in PHP from password_compat, I am not sure what it does: namespace { //… } Is it similar to wrapping some code in an anonymous function in javascript? What’s it purpose? Note: I kn

What does {} mean?

I found this in code, what does it mean and whats the difference between that and normal $dir variable? global ${$dir}; $this->{$dir} = new $class();

In R, what does “loaded via a namespace (and not attached)” mean?

In R, what does it mean for a package to be loaded via a namespace (and not attached) in sessionInfo()? Edit: For example: > sessionInfo() R version 2.15.2 (2012-10-26) Platform: x86_64-apple-dar

Answers

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.

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.

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
   var x;
   var y;
   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 = new Calculate();
 calc.AddCoordinate(5, 20);
 calc.AddCoordinate(3, 16);
 console.log(calc.Slope());
 console.log(calc.Distance());
})();