Learn Basic JavaScript by Building a Role Playing Game - Step 98

Tell us what’s happening:

I don’t need help with copleting the step, just understanding it. This is the code I am fixing in this step:

if (currentWeapon < weapons.length)

I should change the “weapons.length” to “weapons.length - 1”. But why? When current weapon is 4, the same as weapons.length then the if statement should be false, right? Since 4 is not less than 4 it should be false?

If it would say:

if (currentWeapon <= weapons.length)

Then I would understand the fix.

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: script.js */
// User Editable Region

function buyWeapon() {
  if (currentWeapon < weapons.length) {
    if (gold >= 30) {
      gold -= 30;
      currentWeapon++;
      goldText.innerText = gold;
      let newWeapon = weapons[currentWeapon].name;
      text.innerText = "You now have a " + newWeapon + ".";
      inventory.push(newWeapon);
      text.innerText += " In your inventory you have: " + inventory;
    } else {
      text.innerText = "You do not have enough gold to buy a weapon.";
    }
  }
}
console.log(weapons.length)

// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36

Challenge Information:

Learn Basic JavaScript by Building a Role Playing Game - Step 98

currentWeapon is the index, so it can be 0, 1, 2, 3. But if you want to buy a new weapon it should be maximum of 2 so you can buy the final weapon.

And weapons.length is 4.

When we say “currentWeapon < weapons.length”, if you have the final weapon (index of 3) it will return true (3<4) when it should return false. Because we already have the strongest weapon so we can’t buy a new one.

That’s why we need to say “currentWeapon < weapons.length-1”.

I hope you understand :slight_smile: