Meal Maker Project - Type Error(object)

Hi,

For the meal maker project, I am having errors when I ran

let meal = menu.generateRandomMeal();

console.log(meal);

Here is my code

const menu = {

  _courses: {

    appetizers:[],

    mains:[],

    desserts:[],

    get appetizers(){},

    get mains(){},

    get desserts(){},

  },

  get courses() {

    return {

      appetizers: this.appetizers,

      mains:this.mains,

      desserts:this.desserts

    }

  },

  addDishToCourse(courseName,dishName,dishPrice){

    const dish = {

      name:courseName,

      price:dishPrice,

    }

  },

  set _courses(courseName) {

    this.appetizers.push(dish);

  },

  getRandomDishFromCourse(courseName){

    const dishes = this._courses[courseName];

    const randomIndex = Math.floor(Math.random() * dishes.length);

    return dish[randomIndex];

  },

  generateRandomMeal(){

    const appetizer= this.getRandomDishFromCourse('appetizers');

    const main= this.getRandomDishFromCourse('mains');

    const dessert= this.getRandomDishFromCourse('desserts');

    const totalPrice = appetizer.price + main.price + dessert.price;

    return `Your meal is ${appetizer.name}, ${main.name}, ${dessert.name}, The price is $${totalPrice}.`;

  }

};

menu.addDishToCourse("appetizers","Salad", 500);

let meal = menu.generateRandomMeal();

console.log(meal);

ERROR MESSAGE

TypeError: Cannot read property 'appetizers' of undefined
    at Object.getRandomDishFromCourse (/home/ccuser/workspace/learn-javascript-objects-meal-maker/app.js:27:33)
    at Object.generateRandomMeal (/home/ccuser/workspace/learn-javascript-objects-meal-maker/app.js:32:27)
    at Object.<anonymous> (/home/ccuser/workspace/learn-javascript-objects-meal-maker/app.js:42:17)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)

Kindly help
Thanks

It’s because this line const dishes = this._courses[courseName]; is attempting to call your setter method set _courses(courseName) which in turn attempts to execute this.appetizers.push(dish)

this.appetizers doesn’t exist, this._courses.appetizers does. However you shouldn’t call your methods the same as your properties this is what’s confusing matters.

If your property is called _courses then declare your methods as set courses()

1 Like