0
Purpose of Else
So considering an if statement will be skipped if the condition evaluates to false, what is the purpose of having an else statement. To me, it just seems one would just place the code they want to run after the if statement, if the if statement's condition evaluates to false. (that was fun to type lol)
2 Antworten
+ 6
What happens is that you may want to skip the evaluation of other conditions which may be unrelated to the first evaluation, if your first evaluation evaluates to true. E.g. compare the following:
if (x < 0)
{
// codes
}
else
if (y < 0)
{
// codes
}
and
if (x < 0)
{
// codes
}
if (y < 0)
{
// codes
}
The first code tells the program that x < 0 and y < 0 are mutually exclusive, hence only either one is evaluated.
The second code tells the program that x < 0 and y < 0 are independent cases and must be evaluated separately.
+ 2
example of if else statement (javascript):
var x = 2;
var z = "";
if( x%2 == 0 ){
z="even";
}else{
z="odd";
}
console.log("the number is" + z);