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 trialJabor Al thani
2,926 PointsIf and Else if differences?
Im trying to get my mind to understand the differences between If statements and else if statements ?
2 Answers
William Li
Courses Plus Student 26,868 Pointsif (condition1) {
statement1
} else if (condition2) {
statement2
}
In this if..else if examples, if the condition1 happens to be true, the program execution will skip checking the condition2. That's the nature of the else
keyword, else
clause of the conditional will be checked only in the case when the if
clause happens to be false.
if (condition1) {
statement1
}
if (condition2) {
statement2
}
In this example we use multiple if statements instead of if.. else if
. By writing it this way, each if
statement becomes individual codeblock on its own, and they have no connection to each other. Here, the condition2 will ALWAYS be checked regardless of the truthy value of condition1.
Hope this helps.
George Vardikos
6,889 PointsPretty much William Li answer just briefly:
if (something == ball) { go play football } else { go swim } //if something is true then execute otherwise go swim
if(something) {execute} else if (someone) {execute 2} else {shut down} // if something is true execute EXCEPT if someone is true where you will execute 2 BUT if all are false then shut down.