Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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