|
Conditionals
Very often when you write code, you want to perform different
actions for different decisions. You can use conditional
statements in your code to do this.
In JavaScript we have two conditional statements:
· 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 Condition
You should use the this statement if you want to execute some
code if a condition is true, or if you want to select one of two
blocks of code to execute.
If you want to execute only one statement when a condition is
true, use this syntax for the if...else statement, like this:
if (condition)
{
code to be executed if condition is true
}
Notice that there is no ..else.. in this syntax. You just tell
the code to perform one action if the condition is true.
If you want to execute some statements if a condition is true
and execute others if a condition is false, use this syntax for
the if....else statement, like this:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}
Equality Operators
Operator Meaning
== is equal to
!= is not equal to
> is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to
Switch Condition
You should use the this statement if you want to select one of
many blocks of code to execute.
switch (expression)
{
case label1:
code to be executed if expression = label1
break
case label2:
code to be executed if expression = label2
break
default:
code to be executed
if expression is different
from both label1 and label2
}
This is how it works: First we 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.
Examples
1. How to write an if...else statement. Use the if...else
statement if you want to select one of two sets of lines to
execute
Coding
<html>
<body>
<script language="JavaScript">
age = 16
if (age < 18)
{
document.write("Sorry you can not vote!")
}
else
{
document.write("Go ahead and vote!")
}
</script>
</body>
</html>
Output
Sorry you can not vote!
2. How to write an switch statement. Use this statement if you
want to select one of many blocks of code to execute
Coding
<html>
<head>
<script language="JavaScript">
function typeofpayment(payment)
{
switch (payment)
{
case "cash":
alert("You are going to pay cash")
break
case "visa":
alert("You are going to pay with visa")
break
default:
alert("Unknown method of payment")
}
}
</script>
</head>
<body onload="typeofpayment('visa')">
</body>
</html> |