Someone else was asking about the same challenge recently, and the first answer to that might be helpful: Understanding use getters and setters to Control Access to an Object
This challenge has…some issues. I said in the other thread that the more I look at it, the less it makes sense.
Yup, this the main point of getters/setters. They let you run {insert some logic} before you access (via get) or mutate (via set) a “hidden” variable on the object. So if you want to do some logic or validation, but you want that to be hidden from the user of your API, then you can use getters and setters.
I say “hidden” because JavaScript doesn’t (as things stand) have any concept of private variables. In a class-based OO language (Java, C# etc), you can have private variables in classes which a user of the class cannot manipulate directly. That isn’t the case in JS. Anyway, might be clearer with a [possibly] simpler example:
class Rectangle {
constructor(x, y) {
this.x = x;
this.y = y;
}
get area() {
return this.x * this.y;
}
}
This kinda makes sense.
> const myRect = new Rectangle(4, 3)
> myRect.area
12
But you could just do
class Rectangle {
constructor(x, y) {
this.x = x;
this.y = y;
}
area() {
return this.x * this.y;
}
}
Which works kinda exactly the same (note I’m executing a function for area now):
> const myRect = new Rectangle(4, 3)
> myRect.area()
12
NOTE if someone else has an actual good example of getters and setters in JS, that would be great cos I’m at a loss as to an actual usecase that makes sense beyond “I don’t want to have a user of my class have to type some brackets” - they’re the only examples I can find and Google is not being helpful