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
Luc de Brouwer
Full Stack JavaScript Techdegree Student 15,737 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

Jacob Proffer
Jacob Proffer
24,597 Points

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{

}

}