Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
if and elseYou can now create an example script using if and else. In Chapter 4, “Understanding JavaScript,” you created a simple script that displays the current date and time. This example will use conditions to display a greeting that depends on the time: “Good morning,” “Good afternoon,” “Good evening,” or “Good day.” To accomplish this, you can use a combination of several if statements:
if (hours < 10) {
document.write("Good morning.");
} else if (hours >= 14 && hours <= 17) {
document.write("Good afternoon.");
} else if (hours >= 17) {
document.write("Good evening.");
} else {
document.write("Good day.");
}
The first statement checks the hours variable for a value less than 10—in other words, it checks whether the current time is before 10:00 a.m. If so, it displays the greeting “Good morning.”