Organising JavaScript helpers

Introduction

Since 2015 ECMAScript switched to yearly releases and they also switched to new naming format: ES_{Year}.

With the arrival of ES6 or to be correct, ES 2015 we got support for classes in JavaScript. Also, we got new keywords: import and export. And this can make the code much cleaner and easier to work with.

However, even before ES 2015 launched we had the means to use ES2015 functionalities. We were able to use classes and import/export inside of our code. We, of course, had to use some tool to transpile the ES6 to ES5 and we had to use some polyfills so we could make sure that API’s and methods that are built-in with ES6 are available to browsers that still don’t support it.

With ES5 we would use either shared object or some kind of variation on module pattern.

With ES6 we have a built-in support for modules. It is basically a file with JavaScript code inside of it. We can make code from module available for other modules by using export keyword in front of variables, classes, functions. And all code inside of that module is shared. Hence, a lot of people are defining helper methods inside of modules.

However, instead of exporting a bunch of functions from a module, I prefer exporting a class that has static methods that will serve as helpers.

 

The Code

Export of multiple functions

That seems okay. So, far.

If we have a module that imports these helper methods but also imports some additional helper methods, it can get messy. And if function names are similar it gets really hard to read and understand the code.

So, we would have to rename getFullName to getUserFullName and rename getCategory to getUserCategory and then import those methods.

Helpers file:

Usage:

This is fine, but it can get messy if we have multiple imports from multiple files.

 

Cleanest option – Export class with static methods

 I prefer having a class and static methods on it. It seems like a cleaner and more explicit version.

Here is how that looks like

Usage:

Or something like this:

 

Code Sample – GitHub

You can find the code sample on GitHubhere.

Ibrahim Šuta

Software Consultant interested and specialising in ASP.NET Core, C#, JavaScript, Angular, React.js.