We use if/else statements when we have a conditions that we want to test. For example, the condition should come first in the “if” statement. If that condition is satisfied, then the code under that block executes and the rest of the statement is skipped over. However, if the condition is not met, the console will move down and execute the code in the “else” bracket. The basic if/else syntax is as follows:
If (*condition 1*){
*code that will execute if condition 1 is met*
} else {
*code that will execute if condition 1 is not met*
}
Alternatively, you can write more than one condition by using the “if else” statement. There can be as many conditions as you want. The “if” condition statement comes first, and then the other conditions will come under “if else” statements, followed up by an “else” if none of the conditions are met. Typically, if there are many conditions to be tested, programmers will write a “switch” statement, which essentially does the same thing but is just written a little differently.
If statements do not need an “if else” or an “else”—sometimes, you only want to run a program under a certain condition and no other conditions. “Else” statements do not take conditions or Boolean expressions as they are designed to run when no other conditions are met.
Hello Sophie,
Great post, I think you did a good job of explaining how if/else statements work, when the condition is met and not met. These can be very useful for many organizations that need to set a condition. For example, if you spend a certain amount of money, you may get free shipping. That means that if an if/else statement is used you will receive free shipping once you meet that condition but if you do not the system may tell you that you have not met the requirements yet. I think it’s also good that you included the fact that you can have more than one condition for if/else statements. That would mean that you may need to complete two or more requirements for the system to execute the code. Overall, I think you describe if/else statements very well and the example you included added to your explanation.