Namespacing in Javascript

Why bother with namespaces in javascript?
– You get cleaner and more clear code.

It is more clear what “object” or “task” the function and variables belongs to.
Avoids global function conflicts, my function named Calculate() might conflict with another function inside some js file that has been loaded before my js file.

This is one way of doing it, which I personally prefer:

// CompareProducts Namespace:
 CompareProducts = {};

//A new function in that namespace:
 CompareProducts.AddCompareEntry = function () {

//A varible inside the namespace:
CompareProducts.myTestVar = "test test";

//A call to the namespaced function:

//Get variable:

Another way is this (enclose in sub braces)

var yourNamespace = {

    foo: function() {

    bar: function() {


Read even more about it here

Leave a Reply

Your email address will not be published. Required fields are marked *