Development

Writing Clean(er) JavaScript

JavaScript, like many programming languages, has some great ways to compartmentalize and structure code to make it more maintainable, more readable, and more reliable. This post will cover two things that can help developers to organize their code: namespacing and singletons.

Namespacing

While JavaScript has no formal “namespaces,” the ability to have pretty much anything be a member of any object allows developers to emulate them somewhat effectively. You could consider the “window” to be its own namespace, containing what we often refer to as “global” variables. In this sense, everything created in the global scope is actually under the “window” namespace:

[snippet slug=js-window lang=js]

Developers are often discouraged from polluting the window object with variables; this creates several issues that aren’t necessarily Big Problems, but can create headaches and difficult debugging situations in the future.

[snippet slug=js-scope-leak lang=js]

The output above, with commas separating for each call to “console.log”, is:

0, 1, 2, 3, 3, 2, 1, 0

Most programmers familiar with JavaScript and scoping will immediately see why the code above is problematic – the “i” variable in our function “do_something” wasn’t bound to the function’s scope (no use of the “var” keyword). When we called our function, the global “window.i” was accessed and overwritten. Working in the global scope also causes issues with keeping code organized:

[snippet slug=js-clutter-functions lang=js]

In programming, it’s not uncommon to have several functions that do similar tasks but somewhat differently from one another. In a global space, it becomes increasingly difficult to quickly find and parse the available functions. This can lead to duplicating work, confusing function names, and uncertainty for any developer who may come in to work after you. So, what’s a JavaScript namespace? Like just about everything else in JavaScript, you can use an object for a namespace:

[snippet slug=js-decluttered lang=js]

While those two methods don’t appear cleaner and indeed are a little more “wordy” than the original, what they do provide is cleanliness in the form of keeping relevant code separated from the rest of the environment. Instead of hunting through source files, the developer can inspect the “WDS” object and see what properties it has, and add his or her own properties to extend it.

A simple namespacing function can help you to quickly create objects that can be used to organize your code’s functionality:

[snippet slug=js-create_ns lang=js]

Singletons

Another design pattern that helps keep JavaScript clean, both in terms of tidyness and overhead, is the singleton pattern.

Often in programming, we are used to instantiating classes over and over again, but we also want to have classes that we only instatiate once and use them over and over. These are singletons, a good example of a singleton class would be a factory to generate new objects, or a utility class to deal with templating.

[snippet slug=js-template-singleton lang=js]

Using the singleton pattern, we can confidently instatiate the TemplateManager class anywhere in our code and be sure that we’re always dealing with the same instance as the first time we used it: all templates loaded to the utility will be accessible to the object no matter when or where it’s called upon. This also reduces code overhead in the browser, as we aren’t needlessly polluting the environment with multiple objects that all do the same thing.

Conclusion

While JavaScript, and any language really, can be a tangled ball o’ mess, we as developers can do our part to write more maintainable, organizable, and reusable code. Namespaces help keep our code organized into sensible chunks, while singletons create easily reusable classes that can persist their state during the life of a request.

Happy coding!

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupporttwitchunifiedupdatesvaultwebsitewordpress