What does it mean global namespace would be polluted?
I don\'t really understand what global namespace getting polluted means.
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.