Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How can a create an if else statement, that says if something is a property of a specific object

for example I'm creating a simple rpg, and I have a rangedWeapons and a meleeWeapons object that contains different weapons as properties, I need for example an if statement that says if the player equipped weapon is a rangedWeapons property do this.

something like this , I tried putting just rangedWeapons for example but it obviously didnt work

I would have thought there would be a native Object method or something that compares object properties, but I'm not seeing anything. If someone can find any typos keeping this from working or point me in the direction of a native method it would be great, thanks.

if(player.equipped.weapon===rangedWeapons){
                player.equipped.weapon.damage+=10;
            }
            else if(player.equipped.weapon===meleeWeapons){
                   player.equipped.weapon.damage += 5;}

1 Answer

JavaScript Objects allow you to get an array of just all the values on an object, so you can use the includes method on that array to check if the specific weapon you want is in that array. The specific line of code that you would use to do that would look like this:

rangedWeapons.values().includes(player.weapon.equippedWeapon);

You could integrate that into your code like this:

if(rangedWeapons.keys().includes(player.weapon.equippedWeapon)){
    player.equipped.weapon.damage += 10;
}
else if(meleeWeapons.values().includes(player.weapon.equippedWeapon)){
    player.equipped.weapon.damage += 5;
}