
© Royalty Free/CORBIS |
It is possible to respond to the user's input in different ways.
In JavaScript there are three conditional statements:
- if statement — use this statement if you want to execute a set of
code when a condition is true
- if...else statement—use this statement if you want to select one
of two sets of lines to execute
- switch statement— use this statement if you want to select one of
many sets of lines to execute
|
If and If...else Statements
You should use the
if-then statement if you want to execute some code when the condition is true.
Syntax
if (condition){
statement;
statement
}
Example
<script type="text/javascript">
var d=new Date();
var time=d.getHours();
if (time<10) {
document.write("<b>Good morning</b>");
}
</script>
|
This executes some code if the condition is true.
if....else
If you want to execute some code if a condition is true and another code
if a condition is false, use the
if....else statement.
Syntax
if (condition){
statement;
}else{
statement;
}
Example
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10) {
document.write("Good morning!");
}else{
document.write("Good day!");
}
</script>
|
Switch Statement
You should use the Switch statement if you want to select one of many blocks
of code to be executed.
Syntax
switch ( expression ){
case label1:
statement;
break;
case label2:
statement
break;
default:
statement;
}
This is how it works: First you have a single expression
(most often a variable), that is evaluated once. The value of the
expression is then compared with the values for each case in the structure.
If there is a match, the block of code associated with that case is executed.
Use
break to prevent the code from running into the
next case automatically.
Example
<script type="text/javascript">
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
|
Conditional Operator
JavaScript also contains a conditional operator
that assigns a value to a variable based on some condition.
Syntax
o
variable_name=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"Dear President ":"Dear "
If the variable visitor is equal to PRES,
then put the string "Dear President " in the variable named greeting.
If the variable visitor is not equal to PRES, then put the string "Dear "
into the variable named greeting.