Getters and Setters OOP JS

Hi There. Can someone explain to me how getters and setters in JS OOP work? As far as I understood, it’s for protecting the code inside the object. When it comes to protection, the setter method comes in very handy, so you can write a conditional inside it that will prevent updating object properties from outside the object depending on the condition you set. What is the purpose of a getter? I have been struggling to understand this concept very well. Can we live without the getter method and yet have a functional setter, or do we usually need both?

class HospitalEmployee { constructor(name) { this._name = name; this._remainingVacationDays = 20; } get name() { return this._name; } get remainingVacationDays() { return this._remainingVacationDays; } takeVacationDays(daysOff) { this._remainingVacationDays -= daysOff; } } class Nurse extends HospitalEmployee { constructor(name, certifications) { super(name); this._certifications = certifications; } get certifications() { return this._certifications; } addCertification(newCertification) { this.certifications.push(newCertification); } } const nurseOlynyk = new Nurse('Olynyk', ['Trauma','Pediatrics']); nurseOlynyk.takeVacationDays(5); console.log(nurseOlynyk.remainingVacationDays); nurseOlynyk.addCertification('Genetics'); console.log(nurseOlynyk.certifications);

What is the purpose of getters in this code above get name , get remainingVacationDays , get certifications etc… if we only return constructor properties?

It’s a style or paradigm of writing code (object-oriented).
In javascript, there are no true private variables, but you can guide the user to how you want them to use your API by providing getters so they don’t need to worry about what goes underneath (for example, you might change how an class data member is derived or want to sanitize against certain edge cases, etc).

In the wild you’re more likely to see OOP with regards to C++, Java, and C#, maybe less so in JS these days. It’s still useful to know what the principles are and in which cases they might be useful:

Also a small note, you don’t return the constructor properties as much as you return the given instance’s properties. So for example if you have a class Person and you instantiate an instance of Person

joe = new Person("Joe");

joe is considered that one instance.
If you make a new instance, it will not know anything about other instances

mary = new Person("Mary");
mary.getName(); // returns Marys name, not joe's
2 Likes

Aside

This became available only in recent years, not sure exactly when or what iteration of ES:

Private class features - JavaScript | MDN

3 Likes