JavaScript JavaScript and the DOM 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
172,266 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.