Creating maintainable JavaScript code is important if want to keep using the code.
In this article, we’ll look at the basics of creating maintainable JavaScript code by looking at namespacing.
It’s possible that we pollute our single global object even if we only created one.
Therefore, if we have one global variable, we organize our code inside it by namespacing the code.
For instance, we can write:
var Books = {};
Books.JavaScript = {};
Books.Ruby = {}
We have the Books
global variable and we compartmentalize them with properties.
We have the JavaScript
and Ruby
properties to organize different things inside the object.
Also, we can add namespaces dynamically by adding properties to our object.
For instance, we can write:
var GlobalObj = {
namespace(ns) {
const parts = ns.split(".");
let object = this;
for (const part of parts) {
if (!object[part]) {
object[part] = {};
}
object = object[part];
}
return object;
}
};
We have the namespace
function that gets a string that’s separated by dots.
Then we check if the property exists.
If it doesn’t, then we create a property and set it to an empty object.
We do that until all the string parts and added.
And then we return the object
.
This way, we can use it by writing:
GlobalObj.namespace('foo.bar.baz');
And we should see the foo
property with bar
and baz
nested in it.
This method gives us freedom to create the namespace and assumes that it exists.
We just run the namespace
method beforehand so that we can always use it.
#web-development #programming #software-development #javascript #technology