Here is a snippet of JavaScript code from a tutorial I was working with. I don’t understand why it doesn’t end with a final else
clause; I thought that was a ru
else
is a default case
for the if
statement.
If there is no else
then if none of the conditions in the if
or else if
cases are met than the if
statment will do nothing.
Usually it is good practice to have a default case but there are a lot of times where it is not necessary and thus excluded from the code.
In this case, if the curScene
was anything other than 1, 2, 3
then the else
statment would be used, but since there is no processing to be done on other cases the coder has not included an else
.
yes, always have a else is VERY GOOD habit(when using with if-elseif). sometimes people might even write this:
if(curScene == 1) {
message =" welcome";
else if (curScene == 2) {
message = " this is scene two";
}
else if (curScene == 3) {
message = " this is scene three";
} else {
// empty.
}
to tell people there is indeed nothing to do in the else.
It doesn't have to, for the same reason an if
on its own doesn't require an else
.
Usually it's a good idea to have one, as a sort of "catch-all" situation, but the above code could be written as:
switch(curScene) {
case 1: message = " welcome"; break;
case 2: message = " this is scene two"; break;
case 3: message = " this is scene three"; break;
}
In the above code, I could also add:
default: message = " invalid curScene value"; break;
But it's completely optional to do so. It depends on how reliable the curScene
variable is whether or not I personally would add it in.
I thought it was always supposed to end with an "else"?
The else
block is optional. You can have if
without else
.
change the if condition for answer validation if(answer==100) to if(answer===100) it is working fine now...
For the same reason as why you can have just a single if:
if( /*condition*/ ) {
//some code
}
//other stuff