Why it's giving error on "push()"?

I was doing this project “Meal Maker” where i had to write this function.

addDishToCourse (courseName, dishName, dishPrice) {

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

it says: “Cannot read property ‘push’ of undefined” in Error Type
what’s the issue?

this issue has come up so many times on the forum, the problem is that here:

this._courses[courseName]

you use a key which doesn’t exists on courses object

which result in undefined (In my opinion JS should throw an error here). given .push() is a array method, and you try to call this method on undefined, you get an error

you should find out which key you attempt to use that doesn’t exists, you could start by logging (console.log(courseName)) to narrow the problem down

1 Like

How does it work for anyone else? i was watching the Project Walkthrough and he didn’t get such error.
it’s so confusing

Hello, @nameruhollahbayanina, and welcome to the forums.

Do you feel like you have a good grasp on what the addDishToCourse method is supposed to do? Could you describe it to another person? If not, which parts don’t make sense?

The addDishToCourse is to take 2 parameters as strings and dishPrice wish is a number the dish object inside addDishToCourse is to receive the string of dishName and number of dishPrice to value of it’s keys, save it under one variable and push this._courses[coursesName] to “dish”.

I tried to add new property to menu._courses with key of coursesName and with empty array as its value to see if it’s giving error because it can’t find coursesName but error is this “Cannot read property ‘push’ of undefined
at Object.addDishToCourse”

if we insert a .log():

    console.log(Object.keys(this._courses), courseName);
    return this._courses[courseName].push(dish);

we can see the available keys on the object:

["appetizers", "mains", "desserts", "courses"]

and the key you attempt to use:

"Steak"

this key doesn’t exists. Which results in undefined

so here:

menu.addDishToCourse('Steak', 'Salad', 5);

the first argument should be the name of the courses. We can add new dishes (second argument), but only to existing courses.

1 Like