Over a million developers have joined DZone.

The Place Where I Will Use Getters in JavaScript

DZone's Guide to

The Place Where I Will Use Getters in JavaScript

A lot of people believe that using getters in your Javascript is a bad idea. Are there any exceptions to this rule? In this post we take a look at one possible exception.

· Web Dev Zone ·
Free Resource

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

It’s going to be a short one, but powerful.

Do you remember I wrote previously why getters/setters is a bad idea in JavaScript? I didn’t change my mind, I do still think so, but now I found one valid place where I can and DO want use them. You will never guess. (Just kidding.)

Unit tests. Nowadays, I write unit tests and use getters for testing my code. At appears we have a lot of these else, if statements where boolean values are checked, something like this:

function doSomething(options) {
  if (!options.hasZork) {
  } else if (options.hasBork) {

And this is exactly the place where I can now use getters to test whether hasZork has been checked or not. It helps me to protect my API and ensure that all these evil logical branches are tested:

const sinon = require('sinon');

const hasZork = sinon.spy(() => false);
const hasBork = sinon.spy(() => true);

const options = {
  get hasZork() { return hasZork(); }
  get hasBork() { return hasBork(); }


// assert that both hasZork and hasBork has been called;

I promised you it would be a short one. The end!

#1 for location developers in quality, price and choice, switch to HERE.

javascript ,getters ,unit tests ,web dev

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}