What is a namespace in JavaScript?

There was a time when we didn’t have the power of ES2015 JavaScript modules to create applications; so, we had to invent a system to keep our code well-organized, avoid collisions in names, share functions among JavaScript blocks or files, etc. that is when the concept of namespace came into play in the JavaScript world.

For someone coming from Java language, the concept of namespace is basically the same as a Java package, that means is an unique “group of related code”.

How to implement it in JavaScript?

Simple, let’s imagine we are creating a chat application that has configuration (including predefined values), utility functions, etc.

(function(window){
	// 1) Verify no one has created the namespace before
	var Webtraining = window.Webtraining || {};
	Webtraining.chat = Webtraining.chat || {};

	// 2) Create your internal sets of functions or data
	var utils = {
		sendMessage: function () { console.log('Message sent'); }
	};	

	var configuration = {
		welcomeMessage : 'Hello there, how is everything going?',
		logo : '/img/logos/logo-chat.png'
	};

	// 3) Add your sets of functions or data to your namespace
	Webtraining.chat.utils = utils;
	Webtraining.chat.configuration = configuration;

	// 4) Expose your namespace into the global
	if( typeof window.Webtraining === 'undefined' ) {
		window.Webtraining = Webtraining;
	}

})(window);

Previous code will expose the namespace Webtraining.chat in the window, and now you will be able to run:

Webtraining.chat.utils.sendMessage();
// It will print "Message sent"

As you see, you don’t need anything fancy or modern (like Webpack), it is just plain ES5 code. Easy and pretty isn’t it?

See you next time.

Leave a Reply

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