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 trialUnsubscribed User
388 PointsHow come we're using "else if" for the other conditions as opposed to just creating a new "if" statement?
Just curious, I have a logical brain so I'd like to know WHY. :)
2 Answers
andren
28,558 Pointselse if
statements will only be checked if the if
/else if
statements above it did not run.
So for example if we say that item.key
equals "coin" only the first if
statement would be checked, once that runs the else if
statements connected to it are just skipped over entirely without JavaScript even checking what their conditions are.
Which is a good thing since if you know that the item.key
variable equals "coin" then there is no need to check if it is equal to "poison" or "star". That is what makes else if
statements different from if
statements.
Saiful Azhar
2,510 PointsAn else if statement will return right away once the condition is true. Meanwhile, all the if statement will be evaluated regardless if a true statement has been found or not. if and else if is related to each other, while two ifs not.
if(false){
// do something
}
else if(true){
// do something
}
else if(true){ // this won't be evaluated
// do something
}
if(false){
// do something
}
if(true){
// do something
}
if(true){ // this will still be evaluated
// do something
}
Edited: Initially, i used return. If it's in a function, having multiple if which will return once the condition is true, it'll having the same effect as using if else since a return will stop the execution at the point it was called
Both of these are similar
function callMeIfElse(){
var condition = 2;
if(condition === 1){
return;
}
else if(condition === 2){
return;
}
else if(condition === 3){ // this won't be evaluated because a true condition has been met
return;
}
}
function callMeIf(){
var condition = 2;
if(condition === 1){
return;
}
if(condition === 2){
return;
}
if(condition === 3){ // this won't be evaluated because the function has already returned
return;
}
}
Unsubscribed User
388 PointsGot it, thanks!
Unsubscribed User
388 PointsUnsubscribed User
388 PointsAh, got it, thank you. So my guess is that the statements connected to it, that are skipped entirely if item.key equals "coin", is better for loading time? And "cleaner"?