Meal Maker - Getters name & setters

Hello everyone,

I’m trying to put my head around getters & setters for this project, but when I go back to the lesson about getters, it says

Another thing to keep in mind when using getter (and setter) methods is that properties cannot share the same name as the getter/setter function. If we do so, then calling the method will result in an infinite call stack error. One workaround is to add an underscore before the property name like we did in the example above.

Alright, but in the meal maker, the solution shows the getters’ names are the same as the properties… Why ?

Exemple :

const menu = {
  _courses: {
    appetizers: [],
    mains: [],
    desserts: [],
  },
  get appetizers(){
    return this._courses.appetizers
  },

Also, is it fine that a setter and getter have the same name ?

From what I’ve read, the setters & getters use in this project is a bit useless and I think I get why, but this name thing bothers me.
Thanks in advance for the help !

If you did this:

const menu = {
  _courses: {
    appetizers: [],
    mains: [],
    desserts: [],
    get appetizers(){
      return this._courses.appetizers
    },

you would have a problem.

I always like what MDN says because it truly made you understand what is happening:

The get syntax binds an object property to a function that will be called when that property is looked up. (source)

so get appetizers will create a property, but given the other appetizers property is nested within the _courses object, you don’t have a naming conflict.

the advantage of this approach is that we more easily can access the appetizers (menu.appetizers) and other properties. While also enabling us to loop over the different courses if we want to
},

1 Like

Thank you so much, this is much clearer now !