Getters and Setters in JavaScript

Published Jun 26, 2017

Getters and setters are very important in back-end languages, but they never seemed to have gained much popularity in JavaScript. In fact, it’s not an easy task to find documentation about a good way to handle them.

In JavaScript, a value is mostly a value that you can access for read or write freely. But with the rise of large AJAX applications and more and more logic going to the client side, it’s becoming ever more common to have properties that we want to protect from direct access, or even validate before assigning to our objects.

For this purpose, we have the getValue / setValue pattern, which works just like a Java developer would expect: