I’ve always had a love-hate relationship with JavaScript. On one hand, JavaScript will let you easily implement any multitude of sins – similar to languages like Ruby, Python, etc. On the other hand, you can also pull of some pretty neat tricks with an expressive language like JavaScript. As the level of interactivity that people expect from the web continues to increase, much of the logic that used to run on the server side has transitioned to the client side – e.g. executed in the browser via JavaScript. Usability features like auto-complete, date pickers, accordians, etc., can be easily accomplished with JavaScript and libraries like Jquery or MooTools.
Naturally, as we continue to see more and more logic moving from server side to the browser, there comes a greater need for code organization when we build projects and applications with JavaScript. One method for code organization in traditional software applications written in Java and C++ is the concept of a namespace: an abstract container which provides context for the code we write. Using namespaces, we can logically organize objects and classes like “TelevisionShows.Children.MyLittlePony()” instead of using extremely long names like “MyPackage_MyClass_SomeFunction()”.
Aside from saving keystrokes, we also see benefits when we work with other developers. Take for instance the situation where two developers are working on the same project and define a class named “Location”. Both of these developers are unaware that the other is using the same name for a class. To further complicate the matter, developer #1’s Location class is used to define latitude/longitude information, while developer #2’s Location class is used to define street address, city, and zip data. When the two developers combine their code into the final project, chaos will ensue as the interpreter or compiler will not know which definition of Location to use. This is called a namespace collision and happens frequently when developers are working on problems with similar language semantics or abstractions.
Here’s how we fix it in a language like Java:
// File 1: import com.urbaninfluence.GeoLocate.Location;
…
Location myLoc1 = new Location(); // refers to GeoLocate.Location
// File 2: import com.urbaninfluence.Models.Store.Location;
…
Location myLoc2 = new Location(); // refers to Models.Store.Location
Now, when the two developers combine their project code, the namespace collision is avoided and no one has to flip a coin to see who has to refactor their code. Namespacing is a concept that’s been proven to work well in many modern programming languages, so why don’t we use the same concept in a language like JavaScript? Well, because it’s kind of a pain in the ass to be honest. Next I’ll show you how we use namespaces in our JavaScript development to improve code organization, reduce the chances of namespace collisions, and make it easier for developers to abstract ideas into sensible packages.