How to use a setter method instead of push

https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-objects/projects/meal-maker

Hey there, I was thinking about step 8. In the hint, it says “also try using your setter method” I was trying to figure out how to use a setter method instead of push method.

I am still trying to figure out. It would be nice if I could get a little help.

Thanks!

1 Like

The implementation of the setter requires that we write the Array.push method in the setter, not in the addDishToCourse

  addDishToCourse (courseName, dishName, dishPrice) {
    const dish = {
      name: dishName,
      price: dishPrice
    };
    this._courses[courseName] = dish;    // ambiguous
  }

It also requires that we write the property names as backing variables with an underscore.

     _appetizers: [],
     _mains: [],
     _desserts: [], 
    set appetizers (appetizer) {
      this._appetizers.push(appetizer);
    },
    set mains (main) {
      this._mains.push(main);
    },
    set desserts (dessert) {
      this._desserts.push(dessert);
    },

This is not discussed in the video, which example does not even use or need the setter methods.

Note that the getter methods also need to be updated…

    get appetizers () {
      return this._appetizers;
    },
    get mains () {
      return this._mains;
    },
    get desserts () {
      return this._desserts;
    }

As I thought so! In the beginning of the exercise, when we wrote property names without underscore I said to myself, “wouldn’t we need to write these properties if we are to use getters and setters?” Then when I finished the exercise that I noticed we did not event need these setters and getters in the first place. It is sad that video did not explain these parts.

After a little bit of research and after your answer, which I am grateful for, I understand it better. I can push objects into related variables with these setters.

deserts({name: ice-cream, price: 2.00}) etc. 

I guess.
Thanks a lot for being an active member of this nice community!

2 Likes

You’re welcome!

This project has been getting some attention from the back end and may be revised or updated somewhere down the line to bring more clarity to the whole picture, and make full use of getters and setters. We can only wait for that but in the meantime take what lessons you can glean from it. If you can handle the dry technical reading as a side project, dig into the documentation that fully explains them.

3 Likes