Meal Maker - Push seems to be overwriting arrays

Hi all,
I’m sure it’s something silly that I’m missing, but I’m stumped.

To test the script, I call menu.addDishToCourse a bunch of times, so the console should show two meals per course. The console logs the correct number of calls to .addDishToCourse.

However, when I log the array, only the most recent meal is shown in each array. This makes me think that when I push a new meal to a course’s setter, it’s overwriting the existing array.

What’s got me really curious is that when I make a call to one of the setters, it’s not logging a flag to the console.

Any thoughts or hints are greatly appreciated.


const menu = {
  _courses: {
    _appetizers: [],
    _mains: [],
    _desserts: []
  get appetizers() {
    return this._courses.appetizers;
  set appetizers(appetizer) {
    console.log("appetitzer set");
  get mains() {
    return this._courses.mains;
  set mains(main) {
    console.log("main set");
  get desserts() {
    return this._courses.desserts;
  set desserts(dessert) {
    console.log("dessert set");
  get courses() {
    return {
      appetizers: this.appetizers,
      mains: this.mains,
      desserts: this.desserts
  addDishToCourse(courseName,dishName,dishPrice) {
    let dish = {dishName, dishPrice};
    console.log(`course: ${courseName}, meal: ${dishName}`);
    this._courses[courseName] = dish;
  getRandomDishFromCourse(courseName) {
    const dishes = this._courses[courseName];
    let dishIndex = Math.floor(Math.random() * dishes.length);
     return dishes[dishIndex];

menu.addDishToCourse('appetizers','garlic bread','$3.22');
menu.addDishToCourse('mains','rice and chicken','20.00');
menu.addDishToCourse('desserts','green tea icecream','$2.25');
menu.addDishToCourse('desserts','ice cream','$9.00');


you’re only using array.push in your setters
you’re not using your setters
so delete the setters
and then you will still have the same behaviour, thus having ruled array.push out

you should be prepared to dig into your code. it’s not some impenetrable blob. you wrote it, you control it, you observe it.
do a bit of observation, when and where does that overwriting happen?

sidenote: your setters should probably not behave the way they currently do. they’re not setting, they’re appending. there’s a mismatch in semantics there.
if I set something, I’d expect to get back equivalent information when I use a corresponding getter afterwards

1 Like

You are not pushing the course to the array, you are reassigning whole key:value.
Instead call this._courses[courseName].push(dish)