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 Introducing JavaScript Finishing the Game Control the Flow with Conditional Statements

Is this code okey?

I did by myself this code without watching how the teacher does it, I didn't use the If Else, just used the IF. So my question is about if there is a problem of using many IF as I want instead of IfElse?

// when the player collects an item on the screen function itemHandler(player, item) { item.kill(); if (item.key === 'coin') { currentScore = currentScore + 10; } if (item.key === 'poison') { currentScore = currentScore - 10; } if (item.key === 'star') { currentScore = currentScore + 30; } if (currentScore === winningScore) { createBadge(); } }

2 Answers

Brandon Evans
Brandon Evans
8,154 Points

Hi Federico!

Generally speaking, it just depends. Yes, you can use as many if statements as you'd like consecutively, however there could be potential problems depending on what sort of action needs to take place. It ultimately has to do with code efficiency and your needs. In your particular situation, this might be perfectly fine.

It's important to keep in mind that if statements are executed independent of one another - i.e; each statement will run. else if statements will only execute if the previous if's fail.

Hope this helps!

Hey Brandon! Thanks a lot for the explication, I've got it now and I see why to use the else if instead only If. Thanks for your time