Learn Basic JS by Building an RPG - Step 110/117

I’m a little unclear on how some of these things work.

Back on Step 110 it asks: “set fighting equal to 0 - the index of slime in the monsters array.”

My question is, why do you need to do variable = 0 instead of variable = array[0]? I thought you would need to specify which array to get the element out of. Having trouble understanding the rules/logic on that bit.

Then on Step 117, it has you use array[variable].property, and I don’t understand why the variable name goes in the square brackets.

Thanks!

Hi @samwise-webdev

Here is the monsters array:


const monsters = [
 {
   name: "slime",
   level: 2,
   health: 15
 },
 {
   name: "fanged beast",
   level: 8,
   health: 60
 },
 {
   name: "dragon",
   level: 20,
   health: 300
 }
]

ONE
When fighting slime, the code is accessing the first object in the array.

If you use a variable to choose an object, you have more flexibility in how you write the code.

varable.name would be confusing to other programmers.

Having the array[variable].property code structure makes it much easier to read. Someone can also quickly determine which array is used.

TWO
The variable, as mentioned above, accesses the object.

{
   name: "slime",
   level: 2,
   health: 15
 }

Used in conjunction with dot notation, accesses the value of the key.

In monsters[variable].property, the variable is accessing an index of the array.
For example. monsters[0]. name will be the string slime

Happy coding

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.