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 Loops, Arrays and Objects Tracking Multiple Items with Arrays Two-Dimensional Arrays

Why not another 'else if' statement after the first else if statement?

The code I am referencing is:

if (search === 'quit') { break; } else if (search === 'list') { print(inStock.join(', ')); } else { if ( inStock.indexOf( search ) > -1) { print("Yes, we have " + search + " in stock."); } else { print(search + ' is not in stock.'); } }

The current code has an 'if' statement within an 'else'. Why couldn't one just use 'else if'? Is it possible? If not, why? What would happen?

1 Answer

Steven Parker
Steven Parker
229,644 Points

Functionally, you could get the same behavior by converting the nested "if" to another "else if" with a final "else".

But one reason for coding it the way it is would be to keep the tests involving the term itself at one level, and the tests that use it for searching at another level. This could be considered as improved readability now, and reduced opportunity for errors later should additional conditions be needed.

So what you're saying is that it looks cleaner the way that he wrote the code?

Steven Parker
Steven Parker
229,644 Points

From my own perspective, I might not say "cleaner". But you might say it was easier to grasp the intention of the code.

This particular example is simple enough either way that I would personally consider it a matter of "programmer's choice". I was mainly suggesting reasons that someone might think the original style should be preferred.