While creating the Meal maker project here we have an object with a _courses property which holds three properties - appetizers, mains and desserts which each are arrays.
Below is a function of the object that selects a random dish from the array (courseName) we specify.
So the “const dishes” will become the array & in the end the function will return a randomly selected item from the array specified.
getRandomDishFromCourse(courseName) {
const dishes = this._courses[courseName];
const randomIndex = Math.floor(Math.random() * dishes.length);
return dishes[randomIndex];
}
My question is, why couldn’t I do this?
getRandomDishFromCourse(courseName) {
const randomIndex = Math.floor(Math.random() * [courseName]length);
return [courseName][randomIndex];
}
courseName is just a string, which we can use to lookup a key/property in an object (this._courses[courseName]
), doing [courseName]
will create a new array, it isn’t a lookup
3 Likes
Thanks you have cleared this up somewhat. So to say it back to you, the parameter passed through is just a string that happens to have the same name as my arrays. I can’t use it interchangeably but can use it to lookup keys/ properties within an object?
courseName
is the parameter, then when you call the method:
const appetizer = this.getRandomDishFromCourse('appetizers');
you provide an argument ('appetizers'
) for the parameter. Which is just a string. I know, you probably understand it correctly, i am just putting in exactly the right terms now to rule out any misunderstandings
courses
(_courses
, whatever) is an object, an an object has properties, the string has the same “name” as the properties, which have array values
to truly to answer this question, we need to understand that objects are also associative arrays (and vice versa), which results in two styles:
object.property // object notation
array['key'] // associative array notation
only when using the associative array notation, you can use a string to lookup a key
so properties and keys are nearly the same thing, but not quite.
2 Likes