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 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 90,731 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. :-)