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 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
221,902 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.