Once you start building complex applications, there are several factors that will you start to take into consideration. One of those factors is code organization. Although you might not realize the value of code organization when your applications are small in size, when your applications become complex, you will know the value of organized code.

One of the techniques in achieving code organization is called namespacing. Namespaces also help you to avoid collisions with other objects or variables in the global namespace. This is a common problem when working with multiple developers and libraries.

Namespace in JavaScript

Namespacing is essential in an enterprise-level application as you will be integrating several 3rd party scripts that might end up using the same variable or method names as yours. This will lead your code to break as your variables and methods will get overwritten.

It must be noted that JavaScript does not support namespace out of the box, unlike several other programming languages such as C++. But due to the importance of this feature, developers use namespacing patterns to achieve namespacing in JavaScript with the help of objects and closures.

This article discusses only the basic namespacing patterns in JavaScript. For more intermediate and advanced patterns, I would recommend you read Addy Osmani’s book, Learning JavaScript Design Patterns.

Let’s have a look at these patterns.

Single Global Variables

This is one of the most basic and commonly used approaches. This approach uses a single global variable as your point of reference. You will access your methods and variables as properties of this object.

Code Snippet

The above code snippet returns an object with references to the functions from an IIFE.

#node #javascript #technology

Namespace in JavaScript — The Basics
1.45 GEEK