DEV Community

Cover image for Javascript Namespace pattern
George Hadjisavva
George Hadjisavva

Posted on


Javascript Namespace pattern

Namespace Pattern

Namespace can dramatically reduce the number of globals required and at the same time prevents the collisions or excessive name prefixing .
Its important to know that javascript doesn't have namespaces built into the language syntax , but you can achieve this feature quite easy .Instead of adding functions,objects and variables into global scope you can create one global object and add all the functionality

Refactor anti-pattern to Namespace example

Consider this example

//anti-pattern example
function Read() {}
function Speak() {}
var topic_to_learn = "Javascript";
var book1 = {} = {title:"Learn javascript",author:"John doe"}
var book2 = {};
Enter fullscreen mode Exit fullscreen mode

in this example all the functions,variables and objects are declared and polluting the global scope of your application . You can refactor this type of code by creating a single global object for your application , called for example Student and change all functions and variables to become properties of your global object

//Declare the global object
var STUDENT = {}
STUDENT.Read = function(){};
STUDENT.SPEAK = function(){};

//a varibale
STUDENT.topic_to_learn = "javascript"

//object container 
STUDENT.books = {}

//nested objects 
STUDENT.books.book1 = {}; = {title:"Learn javascript",author:"John doe"}
//add second book
STUDENT.books.book2 = {};

Enter fullscreen mode Exit fullscreen mode

This pattern is good way to namespace your code and avoid naming collisions not only in your own code but collisions between your code and third-party code on the same page .

Drawbacks of Namespace

  • More to type , prefixing every variable and function adds up in the total amount of code that needs to be downloaded
  • Only one global instance as a result any part of the code can modify the global instance and the rest of the functionality gets the updated state
  • Long nested names = slower property resolution lookups

Top comments (1)

jonrandy profile image
Jon Randy 🎖️

Or use modules