Search⌘ K

Tip 40: Simplify Interfaces with get and set

Explore how to simplify and protect class interfaces by using getters and setters in JavaScript. Understand how to mask property access with these methods to prevent unexpected data changes and maintain clear, controlled interfaces.

Protecting class properties

You have the basics of classes. You can create instances, call properties, call methods, and extend parent classes. But it won’t be long before someone tries to alter a property you had no intention of exposing. Or maybe someone sets the wrong data type on a property, creating bugs because the code expects an integer, not a string.

One of the major problems in JavaScript is that there are no private properties by default. Everything is exposed. You can’t control what the users of your class do with the methods or properties.

Think about your Coupon. It has a property of price, which you initially set in the constructor. A user of the class can access the property on an instance with dot syntax: coupon.price. So far, no problem. But because an instance of Coupon is just an object, the user can also change the property: coupon.price = 11.

In itself that’s not a big deal. But you’ll eventually hit a problem where another developer (or, admit it, you yourself) innocently tries to set a value other parts of the code may not expect. For example, what if instead of setting the price with an ...