Purpose of Else | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)

3rd Jan 2017, 1:09 AM
Kevin Hewitt
Kevin Hewitt - avatar
2 Answers
+ 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.
3rd Jan 2017, 2:56 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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);
3rd Jan 2017, 1:22 AM
Luis Aguilar Ortiz
Luis Aguilar Ortiz - avatar