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 DOM Scripting By Example Improving the Application Code Refactor 2: Readable Branching Logic

double if else statements

Does anyone know of any good resources for understanding the bracket syntax for using multiple if else statements? After refactoring my code It's a big mess and I've spent a couple hours trying to get it working again.

1 Answer

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 Points

If I understand you correctly you're having a bit of confusion with syntax for an if() statement that happens to have multiple condition blocks. I hope the following is helpful to you in that case.

An if statement can have 3 sections to it.

You have the if statement that contains the original condition or test that a code block has to meet.

if( condition) {
}

And in order to provide the code that occurs when the condition is not met you introduce the elsekeyword.

if( condition) {
} else {

// default condition if not true.

}

Now to test multiple conditions you add more using else if() blocks, which as you've probably seen adds more things for JavaScript to check by passing in more tests in the same way as if().

if( condition) {
    //original condition
} else if ( second_condition) {

    // default condition if not true.

}

You can have as many else if blocks as you want but you will still need the final else block which is where you will put the code to perform the action you do when none of the other conditions evaluate to true.

if( condition) {

    // original condition 

} else if ( second_condition) {

    // default condition if not true.

} else {
    // default condition
}

I hope this has helped you understand what it means to use multiple if else blocks in your condition statements. :-)