Conditional Statement in JavaScript
- Conditional Statements
- JavaScript language supports following type of conditional statements:
-
if
-
if else
-
if else if else
-
Nested if
-
Ternary Operator
-
switch
If Statement
if statement is used to execute some code only if a specified condition is true.
If(<test cond>)
{
//statement
}
If else Statement
if....else statement is used to execute some code if a condition is true and another code if the condition is not true.
If(<test cond>)
{
//statement
}
else
{
//statement
}
If else if else Statement
The if....else if...else statement is used to select one of several blocks of code to be executed.
If(<test condition>)
{
//statement
}
else if(<test condition>)
{
//statement
}
else
{
//statement
}
Nested If Statement
If(<test condition>)
{
if(<test condition>)
{
// statement
}
}Ternary Operator
The ternary operator in javascript is a shorthand of if-else construct and has the following syntax:
<varname>=(<test cond>)?<true>:<false>;
Switch Statement
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}