Hi,
I am having an issue with this project. I keep getting “TypeError: Cannot read property ‘length’ of undefined at Object.getRandomDishFromCourse.”
The error is on line 41, const randomIndex = Math.floor(Math.random() * (dishes.length));
I have defined variable dishes on line 40, so I don’t understand the issue. I’ve followed the video tutorial step-by-step, line-by-line, and cannot figure this out.
Here is my code:
const menu = {
_courses: {
appetizers: [],
mains: [],
desserts: [],
},
get appetizers() {
return this._courses.appetizers;
},
get mains() {
return this._courses.mains;
},
get desserts() {
return this._courses.desserts;
},
set appetizers(appetizers) {
this._courses.appetizers = appetizers;
},
set mains(mains) {
this._courses.mains = mains;
},
set desserts(desserts) {
this._courses.desserts = desserts;
},
get courses() {
return {
appetizers: this.appetizers,
mains: this.mains,
desserts: this.desserts,
};
},
addDishToCourse(courseName, dishName, dishPrice) {
const dish = {
name: dishName,
price: dishPrice,
};
return this._courses[courseName].push(dish);
},
getRandomDishFromCourse(courseName) {
const dishes = this._courses[courseName];
const randomIndex = Math.floor(Math.random() * dishes.length);
return dishes[randomIndex];
},
generateRandomMeal() {
const appetizer = this.getRandomDishFromCourse('appetizers');
const main = this.getRandomDishFromCourse('main');
const dessert = this.getRandomDishFromCourse('dessert');
const totalPrice = appetizer.price + main.price + dessert.price;
return `Your meal includes ${appetizer.name}, ${main.name}, and ${dessert.name}, and costs a total of ${totalPrice}`;
}
};
// add appetizer dish to course
menu.addDishToCourse('appetizers', 'fries', 4.00);
menu.addDishToCourse('appetizers', 'wings', 5.50);
menu.addDishToCourse('appetizers', 'poke', 8.75);
// add main dish to course
menu.addDishToCourse('mains', 'pasta', 15.00);
menu.addDishToCourse('mains', 'salmon', 20.50);
menu.addDishToCourse('mains', 'steak', 25.75);
// add desserts dish to course
menu.addDishToCourse('desserts', 'ice cream', 5.00);
menu.addDishToCourse('desserts', 'pie', 7.50);
menu.addDishToCourse('desserts', 'cake', 9.75);
const meal = menu.generateRandomMeal();
console.log(meal);
Thanks,
adam