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 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
217,572 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
217,572 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.