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 Useful Array Methods

Amy Hsieh
Amy Hsieh
6,023 Points

I thought we can only have one 'else' in a series of if statements?

See the codes from work space:

while (true) {
    search = prompt("Search for a product in our store. Type 'list' to show all of the produce and 'quit' to exit");
    if (search === 'quit') {
        break;
    } else if (search === 'list') {
        print(inStock.join(', '));
    } else {
        if (inStock.indexOf(search) > -1) {
            print('Yes, we have ' + search + ' in the store');
        } else {
            print(search + ' is not in Stock!');
        }
    }
}

or the second else is actually nested within the last if statement? I got confused.

3 Answers

Luc de Brouwer
seal-mask
.a{fill-rule:evenodd;}techdegree
Luc de Brouwer
Full Stack JavaScript Techdegree Student 17,939 Points

Hey Amy,

The code you provided is actually valid! You are completely right about that you can only have one else per if/else.

It can get confusing very fast! There's a thumb rule for using if else statements, if it takes you more than one else if you write a switch statement so you don't have to write all the if/else clausules.

The second else is nested and relative to its parent if, not relevant to the else

Hey Amy,

I formatted your code to make it a little easier to see how the conditionals are set-up. You are correct that there is an additional if/else conditional nested inside of the main else block.

This is probably a good example of where indenting becomes important.

Technically we only have one else statement in the code. You got confused with the two else statement in the code. The first else is the MAIN clause. Inside it contains another if else statement.

else{

if(){

 }else{

}

}