Comparison,
logical and conditional operators
JavaScript is useful when what you want displayed varies depending
on a specific condition. For example, if you want to display the number
of days until Christmas, but only if the current date is after a certain
date, you need to write a conditional statement in your code.
To create a condition, you need one of three types of operators: comparison,
logical or conditional operators. Comparison operators compare the value
of one element to another, which creates a Boolean condition resulting
in either true or false:
y < 100; // if y is less than 100, return true,
otherwise return false
y == 20; // if y is equal to 20, return true, otherwise return false
Note the double equal sign == is a comparison operator, where a single
equal sign = assigns a value.
Comparison operators are:
== Returns true if equal
!= Returns true if not equal
> Returns true if greater than
< Returns true if less than
>= Returns true if greater than or equal
to
<= Returns ture if less than or equal to
A logical operator connects to or more Boolean expressions. Examine
the following:
(x < 100) && (y == 20); // returns true
if x is less than 100 and y is equal 20
Logical operators are:
&& Returns true if both
are true
|| Returns true when either are true
| Returns true if expression is
false and false if expression is true
Conditional operators test whether a specific condition is true and
returns one value if the condition is true and another value if the
condition is false.
(condition) ? value1: value2
message = (mail == "Yes") ? "You have mail": "No
mail";
Using If and If...Else statements
Using comparison, logical and conditional operators allow you to structure
a branch in your routine using the if and if...else statements:
if (Day == "Friday") {
document.write("The weekend is almost
here!");
}
if (Day == "Friday") {
document.write("The weekend is almost
here!");
} else {
document.write("It's not Friday yet");
}
if (Day == "Friday") {
document.write("The weekend is almost
here!");
} else {
if (Day == "Monday")
document.write("Time
for another work week");
} else {
document.write("It's
not Friday yet");
}
}
Use
if...else conditional statements
Edit the code in npntxt.htm:
<script language="JavaScript">
<!-- Hide from old browsers
var Today=new Date(); // Remove initial
value to return system date
var ThisDay=Today.getDate();
var ThisMonth=Today.getMonth()+1;
var ThisYear=Today.getFullYear();
var DaysLeft=XmasDays(Today);
document.write("Today is "+ThisMonth+"/"+ThisDay+"/"+ThisYear+"<br>");
if (DaysLeft > 0) {
document.write("Only
" +DaysLeft+" days until Christmas");
} else {
document.write("Happy
Holidays from North Pole Novelties!");
}
// Stop hiding -->
</script>
Save and view in browser.