Exporting Getters in CommonJS Modules

David Barral
Trabe
Published in
2 min readMar 2, 2020
Photo by Jamie Haughton on Unsplash

I don’t like methods named getStuff. I prefer to have variables named stuff. It feels natural and the code has a different vibe. However, when the stuff value is dynamic you are forced to use a function and have your code full of stuff().

If you use objects you can use getters (obj.stuff) and have the best of both worlds: dynamic values and no unnecessary parens.

To be honest, I never really liked getters in JavaScript. What I disliked was the Object.defineProperty syntax, and I didn’t like the alternative of using get/set named methods either (JavaScript is not Java). But since the introduction of the new get syntax in ES2015 I have been using getters from time to time.

When dealing with CommonJS modules that export dynamic values we tend to export “getter” functions.

Can we export a getter instead?

Yes we can.

You can export whatever you want from a module: some primitive value or a fully fledged object. And any object can have getters.

You can have a dynamic value without explicitly invoking a function. The code has a different vibe just by changing currentDate() to currentDate.

Exporting getters and binding

In general, when you export an object from a module you must be wary of the possible destructuring in the code that makes the require call. Destructuring an object means assigning to a constant one of the object fields. If this field is a function that uses this you must ensure a correct binding.

In most cases, the value of this is determined by how a function is called (runtime binding).

In the case of a getter method, they are always bind to the object that defined them. This means that exported getters are safe to destructure.

In the following example you can see the difference between a normal method and a getter. First implementation breaks when destructuring currentDate2. The second implementation fixes this by explicitly binding the method with bind. The getter works either way.

Should you do this?

Being able to do something does not mean you have to do it. Whenever I write about this kind of stuff I always say the same: Should you do this? It depends 🤷🏽‍♀️.

It’s mostly a matter of personal taste and what works for your project and team.

Currently, we are using this technique only in one specific module of one of our many projects. It made sense to us to do it there. It simplified our code and made it more readable.

I think that’s the correct way to measure this things: does it help you? does it make things simpler? it’s easy to grasp? If you check, check, check, then, by all means, go ahead and use it.

--

--

David Barral
Trabe
Editor for

Co-founder @Trabe. Developer drowning in a sea of pointless code.