Meal Maker - solution video get/set identifier same as the property it's accessing?

In Learn JavaScript > Objects > Project Meal Maker, the solution video has the same get/set property name as the property it’s accessing. But why it’s not going into an infinite loop?
For example, the code below shows while it’s trying to work on the property appetizers. Why is it not going into infinite loop? Or it’s ok if the property the get/set is working on is nested, meaning they are not at the same level/depth (not sure if this is the right way to put…but I mean by that is that the property is not nested in another object, so the property and its get/set method are all not nested) in a object?

Property appetizers has a get/set method that will be defined below.

const menu = {
  _courses: {
    **appetizers**: [],
    mains: [],
    desserts: []
  },
...
}

The get/set method is using the same identifier/property name as the property it’s trying to work on. But I thought it’s forbidden?

get **appetizers**(){
    return this._courses.appetizers;
  },
set **appetizers**(appetizers){
    this._course.appetizers = appetizers;

Codecademy tutorial 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.

…and MDN doc says:

It must not appear in an object literal with another get/set or with a data entry for the same property ( { get x() { }, get x() { } } and { x: ..., get x() { } } are forbidden).

The first one { get x() { }, get x() { } } is easier to understand, but I’m not sure about the second one { x: ..., get x() { } } strictly means it’s forbidden only when the get/set and the property name are at the same level/depth in an object. Because looks like in the example { x: ..., get x() { } } the x is not nested like the appetizers we have here.

Below is a snip of the solution from the video.

Thanks!!

If you have:

// DO NOT RUN THIS CODE
const myObj = {
  x: 3,
  get x()
  {
      return this.x;
  }
}

you have a problem. doing: myObj.x would trigger the getter, which would then endlessly call/invoking itself.

however, because here you work with nested objects, you don’t have this problem.

doing menu.appetizers will trigger the getter. but then accessing return this._courses.appetizers; won’t lead to recursion, because _courses object has getter. Only a property.

if the courses object also had a appetizers getter, you would have recursion/the getter endlessly invoking itself.

1 Like