I just finished the Meal Maker project, and I had a question about something that’s not clear to me.
Just in case it helps, here’s my full code:
const menu = {
_courses: {
appetizers: [],
mains: [],
desserts: [],
},
get appetizers () {
return this._courses.appetizers
},
set appetizers (appetizerIn) {
this._courses.appetizers = appetizerIn
},
get mains () {
return this._courses.mains
},
set mains (mainIn) {
this._courses.mains = mainIn
},
get desserts () {
return this._courses.desserts
},
set desserts (dessertIn) {
this._courses.desserts = dessertIn
},
get courses() {
return {
appetizers: this.appetizers,
mains: this.mains,
desserts: this.desserts
}
},
addDishToCourse(courseName, dishName, dishPrice) {
const dish = {
name: dishName,
price: dishPrice
}
//this._courses.courseName.push(dish)
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(`mains`);
const dessert = this.getRandomDishFromCourse(`desserts`);
const totalPrice = appetizer.price + main.price + dessert.price;
return `Your meal is ${appetizer.name}, ${main.name}, ${dessert.name}. The total price is $${totalPrice}.`
}
}
menu.addDishToCourse('appetizers', 'Fried Mozzarella', 6.00);
menu.addDishToCourse('appetizers', 'Fried Pickles', 5.50);
menu.addDishToCourse('appetizers', 'Barbecue Chicken Flatbread', 8.25);
menu.addDishToCourse('mains', 'Chicken Piccata', 15.00);
menu.addDishToCourse('mains', 'Shrimp Scampi', 18.50);
menu.addDishToCourse('mains', 'Penne alla Vodka', 14.50);
menu.addDishToCourse('desserts', 'Brownie Sundae', 6.50);
menu.addDishToCourse('desserts', 'Tiramisu', 5.00);
menu.addDishToCourse('desserts', 'Pecan Pie', 5.25);
let meal = menu.generateRandomMeal()
console.log(meal);
What I actually have a question about is something that comes up a few times. Here’s an example of where it appears:
addDishToCourse(courseName, dishName, dishPrice) {
const dish = {
name: dishName,
price: dishPrice
}
this.courses[courseName].push(dish);
My question is, why does courseName need to be in brackets here and the other places where it appears? Why can’t we just use the dot notation, like:
this.courses.courseName.push(dish)
Is it because courseName is a parameter in the addDishToCourse function, and those have to be in brackets if we’re using them to drill down into an object location?