Objects Meal Maker Project

https://www.codecademy.com/courses/introduction-to-javascript/projects/meal-maker?action=resume_content_item

On the meal maker project for javascript, why is this._courses[courseName].push(dish); used to push this dish object into the appropriate array in the menu’s _courses object depending on what courseName is passed in?

So, we’d have to push desserts, appetizers, or mains into the courseName?

Why do we need course name in brackets? Because it is an array?

Furthermore .push(dish) will push the object right into the array?

first let look at courses:

const menu = {
  _courses: {
    appetizers: [],
    mains: [],
    desserts: [],
  },
}

seeing how these objects are nested is crucial.

we could write separate functions to append courses to appetizers, mains and desserts, but then we would have a lot of repetitive code, violating DRY.

to avoid this bad repetitive behavior, we make a courseName parameter, allowing is to specify to which course the dish should be added.

Javascript has arrays:

myArray = [1, 2, 3]

objects:

myObj = {a: 1, b: 2}

and associative arrays:

myAssoc =  {a: 1, b: 2}

at this point, i hope you realize objects and associative arrays are the same. Except in the way we access them, we can access an object by using its name:

console.log(myObj.a)

or with the associative array notation:

console.log(myAssoc['a'])

see how i know use brackets? We can’t do:

console.log(myObj.'a')

when we want to access an property of an object with a string, we have to use the associative array notation.

1 Like

so dish is an associative array

yes and no, objects are associative array and vice versa. Its a weird quirk of the JS language.

I mean associative arrays look like objects, so that’s why I’m confused on how to differentiate

They don’t just look alike, they are the same. Except in the way we access a property/key (.property vs ['key'])