Getters and Setters: When to use and when not to

Hi All,

I am trying to wrap my head around the “why” of getters and setters and a little more about there limitaitons.

In the Meal Maker project we go through and add a whole bunch of these right at the start and I understand that we have a little indication not change the object etc but I want to understand what the context of that decision is so that I understand where I would and would not use them in the future.

From the documentation MDN mentions that getters and setters create a kind of pseudo-property. It sort of implies that the value you have collected and given the key is both there and not at the same time. So here are my questions.

  • Contextually, am I choosing not to actually change the ‘courses’ object because in the real world I would go to lots of restaurants and the meals would be different each time. There is therefore no point actually retaining the value of each course outside of that restaurant visit?

  • Given the getter and setters are working with pseudo-properties. Can I call the outcome of a setter outside of the object I have used them in? All our functions in Meal Maker are inside the menu object, I assumed that was so we could use this. but is it also so we can use the outcome of our getters and setters?

I am really enjoying this course but I am learning there is so many ways you can get to a single outcome and I am trying understand why you would pick a certain path. Sorry if the questions are super basic! haha

Thanks

This is a common source of confusion for learners, so don’t be discouraged. My own opinion is that getters and setters are not very important until you begin using ES6 classes. In that context, there are a bunch of reasons for why and when you may want to use getters and setters, but for plain old ES5 objects, it’s probably not important enough to get hung up on it.

Javascript’s way of handling getters and setters in ES5 is just plain weird and contrary to how it is done in other programming languages. My answer is a bit of a cop-out because I’m just saying don’t worry too much about it for now, but I’ve never came across a use case for them outside of defining classes. Just my 2 cents.

1 Like