Meal maker Project

Hello!

I am confused on why on the Meal Maker Project underscores are not used for the keys appetizers, main and dessert when the getters and setters have the same name. For what I remember on the theory lessons is a common use to add _ to those keys so names are not the same and create a loop.

from the docs:

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

so when we use get a property with that name is created, and when that property is looked the bound function is called.

the underscore is a convention, this is also allowed:

const example = {
  a: 3,
  get b() {
     return this.a;
  }
}

console.log(example.b) // logs: 3

But this is weird and confusing (a = b, not very logical), so the underscore is a good naming convention

What you need to prevent is that getter property looks up itself, which would need to endless recursion (function calling itself)

this would be a problem:

  get appetizers(){
    return this.appetizers;
  },

the property looking up itself.

Which is not the case when you nest the property in another object

1 Like

From what I understand, the underscore is used to mark a key or variable as meant to be private while JavaScript itself doesn’t make this difference. So apart from the necessity of avoiding duplicate keys, leaving the underscore for getters and setters makes sense semantically, because it simulates making the accessed keys publically available (even though they’ve never been private). From this background, I think the question, why appetizers, mains and desserts are written without an underscore is eligible. Or am missing something?

True, but given this isn’t enforced by JavaScript I mostly see the private notation for properties which have a getter

it is, and I explain it? The getter property doesn’t look-up/access itself because of the nesting in another object.

That’s not what I meant as it refers mainly to the duplicate key issue.
What I mean is, why not this:

_courses: {
    _appetizers: [],
    _mains:[],
    _desserts:[],
  }
get appetizers(){
    return this._courses._appetizers;
  }

as it would make more sense semantically, because semantically these keys would be private unless there is a getter.

Thank you for the explanation. I think what I was missing to understand this is the fact that the property is nested in another object.

Now things make better sense of why it doesn’t create a feedback loop.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.