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 trialLuca Di Pinto
8,051 PointsWhy do we use "else if" and not "else"?
As per question, why do we use "else if" in the statement" instead of "else"?. Isn't "else if" used in multiple statement? Here we have only one! I do not understand!
3 Answers
Steven Parker
231,236 PointsThe use of else if is to limit when the code will run.
The event handler will be invoked for any button, but the if and else if are used to run code only on the "remove" and the "edit" buttons. If the "else if" were replaced with "else", then the code intended for the the "edit" button would run when any button other than "remove" was clicked.
This might not seem important if there are only those two button types in the list, but it could cause big trouble in the future if another button type was added to the list.
Franklyn Roth
16,770 PointsIt ends up being easier to maintain and lets say the client wants to add additional buttons, would be much easier of a feature to implement if their is a method like the conditional checks applied using else if vs only checking one condition with else.
Luca Di Pinto
8,051 PointsThanks Steven,
but if I should have only two buttons does it make sense to use "else" instead of "else if"? What you say is valid only if in the future i should add other buttons, isn't it?
Steven Parker
231,236 PointsYes, but it also makes the intent of your code clear. For both of these reasons it is a "best practice" that will make continued maintenance of the code easier.