What does it mean global namespace would be polluted?
I don't really understand what global namespace getting polluted means.
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:
In the example above,
x
is declared in the global scope. Any child scope, such as that created by theexample
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:
Global variables are usually not recommended because of the potential to cause problems like this. If we didn't use the
var
statement inside theexample
function, we would have accidentally overwritten the value ofx
in the global scope: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:
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:
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.
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)
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.