All programming languages provide flow control statements that allows you to control the order in which the code is executed. These control statements enable your program to follow a certain course of action depending on whether a particular condition is met. These conditions are always comparing between variables and data. Some sample conditions are follows:
- Is X is bigger than Y ?
- Is Y is smaller than X ?
- Is X is equal to Y ?
- Is X is not equal to Y ?
If you notice the above statements you can see a similarities in the answer of the above conditions. Right....the answer should be YES or NO.
The condition in the if statement is true then the code in the statementBlock will be executed.
The above example evaluate 10 is greater than 5 or not. If the condition is true then the code block will execute. Here the condition is true, so the code block will execute your code inside the curly braces.
If you face two possible situations and you want to respond differently for each, then you can use an if...else statement.
In the above syntax, program check first statement expression is true, if it is true then first statement block will execute otherwise second statement block will execute
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.
Alternative if..else Syntax (? Ternary Operator)
Instead of using if..else statement, you can use shorthand conditional expressions.
A normal if...else syntax example.
Using Ternary Operator(?)