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 accomplish 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.
?: Run character
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>
Question mark operator
<title>a Simple page</title>
<script language= "JavaScript" >
<!--
var w = 1, x = 2, y = 3, z = 4, ans;
Ans = (w > x)? Y:z
alert (ANS);
-->
</script>
<body>
</body>
Example Two
<script language= "Web Effects" type= "Text/javascript" >
<!--
Confirmval = Confirm ("click");
Alertstr = Confirmval? "You clicked OK": "You clicked Cancel";
alert (ALERTSTR);
-->
</script>
?: operator
<title>finding the absolute value</title>
<SC Ript language= "javascript" type= "Text/javascript"
<!--
function f ()
{
& nbsp var MyVar = prompt ("A number", "");
var themodulus = (myvar>=0)? MyVar:-myvar;
var msg = (isNaN (themodulus))? "Numbers only.": "The modulus's" + MyVar + "is" + themodulus;
alert (msg);
}
//-->
</script>
<body>
<a href= "javascript:f ()" >get absolute value</a>
</body>
</ Html>