Cookie Doe
Cookie Doe

Reputation: 13

JavaScript TypeError, Cannot read property of undefined, but the function is defined. What am I doing wrong?

I keep getting the error: "TypeError: Cannot read property 'push' of undefined"

The error is in this line: "this.courseName.push(dish);"

Here is the code:

let menu = {
    _courses: {
      _appetizers:[] ,
      _mains:[],
      _desserts: []
    },

    addDishToCourse(courseName, dishName, dishPrice){
        const dish = { name: this.dishName, price: this.dishPrice };

        // ERROR HERE: **this._courses[courseName].push(dish);**
    },
};

I have been stuck with this error for hours. Is there something I'm not seeing?

Sorry if there is a simple solution to this. I'm relatively new to JavaScript.

Edit:

I was indeed calling the key incorrectly. I am now calling the function as:

  menu.addDishToCourse("_appetizers", "random", 10);
  console.log(menu._courses._appetizers);

When I log this in compiler it returns:

    [ { name: undefined, price: undefined } ]

It seems like the function isn't getting called. Am I approaching this fundamentally incorrectly?

Upvotes: 1

Views: 1145

Answers (2)

cнŝdk
cнŝdk

Reputation: 32145

Your first problem is that you were passing a wrong courseName to the function, that's why you get the error.

And your second problem is that you are assigning wrong values, to object to push in your courses array when you used { name: this.dishName, price: this.dishPrice }.

In fact when you use this.dishName you were trying to get dishName from your menu object that's why it's undefined, you just need to use the parameters dishName and dishPrice you are passing arguments to the function.

    const dish = {
      name: dishName,
      price: dishPrice
    };

    this._courses[courseName].push(dish);

This is a working Demo:

let menu = {
  _courses: {
    _appetizers: [],
    _mains: [],
    _desserts: []
  },

  addDishToCourse(courseName, dishName, dishPrice) {
    const dish = {
      name: dishName,
      price: dishPrice
    };

    this._courses[courseName].push(dish);
  },
};


menu.addDishToCourse("_appetizers", "random", 10);
console.log(menu._courses._appetizers);

Upvotes: 1

Steve Padmore
Steve Padmore

Reputation: 1740

It is the scope that is the issue.

this is the object itself (the menu in this case) and has _courses and addDishToCourse as its properties.

Inside the addDishToCourse this is looking at the object for the dishName and dishPrice, but they are scoped to the function itself (from the parameters).

So the correct code would be like so:

let menu = {
        _courses: {
            _appetizers: [],
            _mains: [],
            _desserts:[]
        },

        addDishToCourse(courseName, dishName, dishPrice) {
            const dish = { name: dishName, price: dishPrice };

            this._courses[courseName].push(dish);
        }
    }    

menu.addDish("_mains", "Pizza", "10");

Upvotes: 1

Related Questions