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 JavaScript and the DOM (Retiring) Traversing the DOM Solution: Using nextElementSibling

Noah Fields
Noah Fields
13,985 Points

Why aren't you using "else if"?

Instead of a large number of independent if statements next to each other, a group of connected 'else if' statements could be used here for each button. Doing so comes at no risk of malfunction or necessity to rewrite later (unless there's some expectation of, say, eventually needing to move a button up and also deleting it at the same time for some reason), and also will help the webpage run more quickly from potentially only checking one or two statements instead of three.

With all this in mind, what is the purpose of using if statements instead of else if?

1 Answer

Steven Parker
Steven Parker
231,264 Points

As is, the code has a more unified structure and is slightly more compact than using an "if...else if" chain. But you're right, you could use such a chain and it would give slightly higher efficiency depending on which button was chosen.

But as the entire block of code only runs on demand when a button is manually clicked, any efficiency improvement would not be detectable by the user.

I don't know if this was intended by the instructor, but I would personally tend to choose code compactness over efficiency in cases where the efficiency would not be detectable.