MealMaker stuck on an error

i’m getting the following error ‘TypeError: Cannot read property ‘length’ of undefined’ from the getRandomDishFromCourse function (const randomIndex = Math.floor(Math.random() * dishes.length);) and i’m not sure how to fix it.

const menu = {
__courses: {
  appetizers: [],
  mains: [],
  desserts: [],
get appetizers(){
  return this.__courses.appetizers;
get mains(){
    return this.__courses.mains;
get desserts(){
    return this.__courses.deserts;
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,
  const dish = {
    name: dishName,
    price: dishPrice,
  return this.__courses[courseName].push(dish);
  const dishes = this.__courses[courseName];
  const randomIndex = Math.floor(Math.random() * dishes.length);
  return dishes[randomIndex];
  const appetizers = this.getRandomDishFromCourse('appetizers');
  const main = this.getRandomDishFromCourse('main');
  const dessert = this.getRandomDishFromCourse('dessert');    
  const totalPrice = appetizer.price + main.price + dessert.price;
  return `Your meal is ${}, ${} and ${}, and the total price is ${totalPrice}`;

menu.addDishToCourse('appetizers', 'Salad', 4.00);
menu.addDishToCourse('appetizers', 'Wings', 5.00);
menu.addDishToCourse('appetizers', 'Fries', 6.30);

menu.addDishToCourse('mains', 'Steak', 8.00);
menu.addDishToCourse('mains', 'Chicken', 12.00);
menu.addDishToCourse('mains', 'pasta', 7.80);

menu.addDishToCourse('desserts', 'ice cream', 3.00);
menu.addDishToCourse('desserts', 'Cake', 5.00);
menu.addDishToCourse('desserts', 'cheese board', 9.80);

const meal = menu.generateRandomMeal();

first step would be to see what is actually causing the undefined, we could simple log some relevant variable:

  const dishes = this.__courses[courseName];
  console.log(dishes, courseName);

so things go well for appetizers, but then for main things go haywire.

looking at the properties courses object has, I can see why


I fixed it by changing any instance of main or dessert to mains and desserts. However i’m not entirely sure how it works to be honest.

we can use strings to access properties on objects using associative array notation:

console.log(myObj['key']) // get value belonging to key of myObj

the problem is, JS doesn’t throw an error when we try to access a property/key which doesn’t exist. Resulting in a misleading error.