All programming languages provide flow control statements that allows you to control the order in which the code is executed. A conditional statement is a set of rules performed if a certain condition is met. These conditions are always comparing between variables and data.
- if statement
- if-else statement
- if...else if...else statement
- ternary statement or ternary operator
- switch statement
The statements gets executed only when the given condition is true. If the condition is false then the statements inside if statement body are completely ignored.
Here "conditionExpression" is a boolean expression (returns either true or false). The if statement evaluates the conditionExpression inside parenthesis. If conditionExpression is evaluated to true (nonzero) , statements inside the body of if is executed. If statementBlock is evaluated to false (0) , statements inside the body of if is skipped.
The else statement is to specify a block of code to be executed, if the condition in the if statement is false.
In the above syntax, the if statement evaluates the conditionExpression inside parenthesis. If the resulting value is true, the given statementBlock in the "if" block, are executed. If the expression is false, then the given statementBlock in the else block are executed. The else clause of an if...else statement is associated with the closest previous if statement in the same scope that does not have a corresponding else statement.
If you face more than two possible situations and you want to respond differently for each, then you can use an if...else if...else statement. It evaluates the content only if expression is true from several expressions.
In the above syntax, it is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.
You got second grade!!
ternary statement or ternary operator
Instead of using if..else statement, you can use shorthand conditional expressions.
Noraml if...else statement
Using Ternary Operator(?)
Switch case statements are a substitute for long if statements that compare a variable to several integral values (if...else if...else). When you want to check a particular condition for a large number of possible values, switch statement is a more efficient alternative of if...else if...else statement.