Object Question

Hey quick question. I’m doing the JavaScript Algorithms and Data Structures (beta) course and doing the learn algorithms by building and RPG game exercise. My variable name is locations and contains an object. When I refer to that object inside my update function I use the word location (notice how its singular) but the code still functions. How does this happen?

const locations = [
  {
    name: "town square",
    "button text": ["Go to store", "Go to cave", "Fight dragon"],
    "button functions": [goStore, goCave, fightDragon],
    text: "You are in the town square. You see a sign that says \"Store\"."
  },
  {
    name: "store",
    "button text": ["Buy 10 health (10 gold)", "Buy weapon (30 gold)", "Go to town square"],
    "button functions": [buyHealth, buyWeapon, goTown],
    text: "You enter the store."
  }
];

// initialize buttons
button1.onclick = goStore;
button2.onclick = goCave;
button3.onclick = fightDragon;

function update(location) {
  button1.innerText = location["button text"][0];
  button2.innerText = location["button text"][1];
  button3.innerText = location["button text"][2];
  button1.onclick = location["button functions"][0];
  button2.onclick = location["button functions"][1];
  button3.onclick = location["button functions"][2];
  text.innerText = location.text;
}

Hello @williamjonahmci!

This is a great question. Your variable locations is an array of objects and can be referenced in a number of ways.

locations[**arrayname**[*element number*]][**object property** ][*element number*]

A codepen has been created with a portion of your code for you to experiment with.

If your code is working, it could be a caching issue with your browser or some other anomaly - unless I am mistaken - and that has never happened before :rofl:

Keep up the good work.

Happy coding.

1 Like

you are not referencing the locations array here. Here you are just writing the update function which has a location parameter.
If you ever call the function like:

const myHouse = {
  {
    name: "house",
    "button text": ["Play videogames", "Eat dinner", "Go to town square"],
    "button functions": [playGame, eat, goTown],
    text: "Welcome home!"
  }

update(myHouse);

then you will be referencing a specific object, and that will be the value of the location parameter inside the function.

Once you finish writing the update function I’m sure there will be the steps that ask you to call it with specific values, and then you will be using the locations array

1 Like