Conditional statement
When you write code, you often need to perform different behaviors according to different conditions. You can use conditional statements in your code to
Complete this task.
In JavaScript, we can use the following conditional statements:
If statement
Executes code when a specified condition is set up.
If...else statement
Executes code when the specified condition is set up, and executes additional code when the condition is not valid.
If...else If....else Statement
Use this statement to choose to execute one of several block of code.
Switch statement
Use this statement to choose to execute one of several block of code.
If...else If...else Statement
Use the If....else if...else statement when you need to select a set of multiple sets of code to run.
Grammar:
if (condition 1)
{
Condition 10% Execute code immediately
}
else if (condition 2)
{
Condition 20% Execute code immediately
}
Else
{
Execute code when both condition 1 and Condition 2 are not true
}
Instance:
<script language= "JavaScript"
<!--
Mailflag = " YES
var message1;
var message2;
if (Mailflag = = "YES") {
message1 = "A";
}else{
message1 = "B";
}
//same statement using conditional operator
Message2 = (Mailflag = "yes")? "A": "B";
document.write ("The If Statement returns:", Message1, "<BR>");
document.write ("The Conditional operator returns:", Message2);
;
</script>