Conditional
statements use conditional operators on variables to make decisions in
code. The standard conditional statements are:
·
if statement - This statement allows you to execute a piece
of code only if a specified condition is true.
Syntax:
if
(expression)
{ Statement;}
Example:
<html>
<body>
<script
type="text/javascript">
var
a = 10;
var
b= 10;
if
( a==b)
{
document.write("The
values of a and b are equal!");
}
</script>
</body>
</html> |
·
if...else statement - This statement allows you to select which
of the two pieces of code to execute depending on the condition. If the
condition is true then the first piece of code is executes else another
piece of code is executed.
Syntax:
if
(expression)
{ Statement;}
else
{ Statement;}
Example:
<html>
<body>
<script
type="text/javascript">
var
a = 10;
var
b= 12;
if
( a==b)
{
document.write("The
values of a and b are equal!");
}
else
{
document.write("The
values of a and b are not equal!");
}
</script>
</body>
</html> |
·
if...else if....else statement - This statement allows to select
one of the many blocks of code to be executed.
Syntax:
if
(expression)
{ Statement;}
else
if (expression)
{ Statement;}
else
{ Statement;}
Example:
<html>
<body>
<script
type="text/javascript">
var
age = 18;
var
b=15;
if
(b >= age)
{
document.write("You
are eligible to vote!");
}
else
if (b < age)
{
document.write("You
are not eligible to vote!");
}
else
{
document.write("Please
enter your age!");
}
</script>
</body>
</html> |
·
Switch… case - This statement also allows you to select one of
the many blocks of code to be executed. This is quite similar to if...else
if....else statement but it is more useful when all the values of a variable
needs to be checked.
Syntax:
switch
(expression)
{
Case
label :
{ Statement1;
Break;
Case
label 2:
{ Statement2;
Break;
Default:
Statement3;
}
Example:
<html>
<body>
<script
type="text/javascript">
var
dateobj=new Date();
var
today=dateobj.getDay();
switch(today)
{
case
(1):
document.write("Today
is Monday!");
break;
case
(2):
document.write("Today
is Tuesday!");
break;
default:
document.write("Today
it is neither Monday nor Tuesday");
}
</script>
</body>
</html> |
|