Why is it bad to have all your script code available at global level?
First of all you can possibly get a lot of errors when using modules developed by others, because you used the same names for you variables etc.
The second reason is, this code can’t be minified as good as the code I will show you later.
In my example I will use a pattern like in the first article because it will allow me to control visibility.
This way of writing your code looks pretty much like writing your code in c# or Java, isn’t it (except from the syntax).
But we are still polluting the global namespace. Now there are only two variables, but think of it when you complete the code I started. How many modules would be added? How much more you will be polluting the global namespace?
When opening the developer tools in for example Chrome and hitting F12 and navigating to the console tab and you type ‘product’ or ‘shoppingCart’ and hit the enter key you can access the objects from the global namespace.
So how can we wrap these modules in our own namespace?
As you can see we build a little wrapper around our modules. This wrapper is a self executing function which provides access to the elements from the global namespace. When calling this anonymous self executing function we provide our own namespace which we register at global level. We also provide window, document and undefined, because this gives advantages in performance and minification of your scripts. When you never use them in your script you don’t need to add them, but as a best practice I always add them so I will never forget them. Please note that the last parameter isn’t provided, so it is undefined.
Another best practice is to start each script with a semicolon, so you don’t have to bother about missing semicolons in other scripts. By starting with one at least this script file will not give errors on behalf of missing semicolons in other files. Issues most of the time occur when minifying your scripts.
Last but not least we have to register our module in our namespace. What we do is checking if the module already exists or else replace it with your module definition.
You may be asking, what if I want to use jQuery or whatever other script? Just add it to the wrapper so you can use it in you module.
As a last advice…
Subscribe to Addy Osmani’s RSS Feed.