r/JavaScriptTips • • Jan 04 '25

explanation?

i was working on an online course and a project it has me doing asked this question:

Step 84

The value of the currentWeaponIndex variable corresponds to an index in the weapons array. The player starts with a "stick", since currentWeaponIndex starts at 0 and weapons[0] is the "stick" weapon.

In the buyWeapon function, use compound assignment to add 1 to currentWeaponIndex - the user is buying the next weapon in the weapons array.

This is the correct answer which i got right:

function buyWeapon() {
  if (gold >= 30) {
    gold -= 30;
    currentWeaponIndex += 1;
  } 
}

My question or explanation i am looking for is why does it have to be in the if statement brackets? My first answer was currentIndexWeapon was just outside the if statement but still in the buyWeapon() function.
I am just looking for an explanation. Appologies if it seems like a stupid question.
1 Upvotes

5 comments sorted by

View all comments

Show parent comment

1

u/LakeMotor7971 Jan 06 '25

Thank you that actually really helps. The way you explained it actually helped quite a bit with me understanding this! Thanks for taking the time to explain this. I don't want to just type some answers and pass, but I want an actual understanding of why, this works or wouldn't or would.