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

Howie Yeo
PLUS
Howie Yeo
Courses Plus Student 3,639 Points

Else if clause not nested together?

Hey all, Can anyone explain why is the 'else clause' and 'if clause' not together in one line ? ( aka 'else if clause') This below code looks like it can an regular 'else if' clause?

else {
      if ( inStock.indexOf( search ) > -1 ) {
        print('Yes, we have ' + search + ' in the store.');
      } else {
        print( search + ' is not in stock.' );
      }
   }

2 Answers

Hi,

I think you are asking if if else can not be on the same line. Writing this is valid:

if() {
// do
} else if () {
// do something else
} else {
// else
}

It depends on what the if condition as checking at the beginning if you want to use if else. if you are checking for more than one conditions.

I guess it could have been another else if and then the final else in this case. It will work either way, I think Dave just wanted to show how you can nest conditionals.