Conditionals are control structures that perform different actions depending on the value of an expression.
if-else
The if statement allows to make decision and to execute statement conditionally. If the condition evaluates to true, statement is executed, otherwise it is not.
if (condition) statement;
To conditionally execute more than one statement you should use curly braces like below:
if (condition) { statement1; statement2; }
It is considered good practice to always enclose code within braces even if only one statement is to execute.
Using an else clause allows to execute another statement if the condition is false:
if (condition) { statement1; } else { statement2; }
You can also combine a few if-else statements:
if (condition1) { statement1; } else if (condition2) { statement2; } else { statement3; }
An example:
if (weight <= 60) { category = "light"; } else if (weight > 60 && weight <= 90) { category = "middle"; } else { category = "heavy"; }
switch
The switch statement is similar to the if-else statement. If all of the branches depend on the value of the same expression, the switch control structure can be used instead of the if-else.
switch (expression) { case value1: statement1; [break;] case value2: statement2; [break;] default: statement3; }
When the switch statement is executed, the program attempts to match the value of expression to a case valel. If the value of expression is equal to a case value, the program executes the associated statements. If matching is not found, the program looks for the optional default clause. If it is found, associated statements are executed, if not the program skips all statements within the switch statement.
The optional break keyword associated with each case ensures that the program breaks out of the switch statement once the matched statement is executed. If the break is omitted all subsequent statements will also be executed.
An example:
switch (option) { case 1: type = "small"; break; case 2: type = "medium"; break; case 3: type = "large"; break; default: type = "other"; }
Reply