Home > Back-end >  Uncaught TypeError: Cannot read properties of undefined (reading '2') happens while using
Uncaught TypeError: Cannot read properties of undefined (reading '2') happens while using

Time:11-04

i was learning array destruction from objects and then it should return two values as the order function says but it doesnt

const restaurant = {
    name: 'Classico Italiano',
    location: 'Via Angelo Tavanti 23, Firenze, Italy',
    categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
    starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
    mainMenu: ['Pizza', 'Pasta', 'Risotto'],
    order: (starterIndex, mainIndex) => {
        return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
    },
};

console.log(restaurant.order(2, 2));

And i got this in the Browser Console and also node js console:

**

Uncaught TypeError: Cannot read properties of undefined (reading '2')
    at Object.order (main.js:153:33)
    at main.js:157:24

**

CodePudding user response:

Arrow functions do not have their own 'this' you can use a regular function declaration, see if this post helps: this inside object

const restaurant = {
    name: 'Classico Italiano',
    location: 'Via Angelo Tavanti 23, Firenze, Italy',
    categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
    starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
    mainMenu: ['Pizza', 'Pasta', 'Risotto'],
    order: function(starterIndex, mainIndex) {
        return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
    },
};

console.log(restaurant.order(2, 2));

  • Related