Conditional statements allow program to make correct decisions and perform right actions based on certain conditions. The situation may be when you need to adopt one out of a given set of paths. For this, JavaScript supports conditional statements are used to perform different actions based on different conditions.
Conditional statements in JavaScript are of following two types:
The forms of ‘if..else’ statements supported by JavaScript are:
This is simple if statement, and if condition (expression) is true, the block of code is executed. If the expression is false, then no statement would be executed. Mostly comparison operators are used while making decisions.
Syntax:
if (expression)
{
Code block to be executed if expression is true
}
The 'if...else' statement is the standard if then else statement. In this, if condition (expression) is true, then ‘if’ block of code is executed. If the expression is false, then the ‘else’ block of code would be executed.
Syntax:
if (expression)
{
Code block to be executed if expression is true
}
else
{
Code block to be executed if expression is false
}
The ‘if...else if...’ statement is an advanced form of ‘if…else’ statement having a series of if statements which allows to make a decision out of several conditions (expressions).
Here, each if is a part of the else clause of the previous statement. Block of codes for each part is executed based on the true condition of that expression, if none of the conditions is true, then the else block is executed.
Syntax:
if (expression-1)
{
Code block to be executed if expression-1 is true
}
else if (expression-2)
{
Code block to be executed if expression-2 is true
}
else if(expression-3)
{
Code block to be executed if expression-3 is true
}
...
else
{
Code block to be executed if no expression is true
}
To perform a multi-way branch operations having multiples expressions we may use multiple ‘if...else if…’ statements when operations to be performed on only one condition. To do similar task in easier manner, switch case statement may be used. Switch case do this kind of executions more efficiently than repeated ‘if...else if...’ statements.
The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The system checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used
The following flowchart shows the switch case:
Syntax:
switch (expression)
{
case condition 1:
code_block1
break;
case condition 2:
code_block2
break;
...
...
...
case condition n:
code_blockn
break;
default:
code_block
break;
}
The break statements indicate the end of a particular case, once a condition is matched, if break is specified, the execution of remaining code of switch is not executed and control transfers after the statement of switch case. If break is omitted, system will check each code block in each of the remaining cases