Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 18. Controlling Flow with Condit... > Testing Multiple Conditions with if ...

Testing Multiple Conditions with if and else

You 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.”


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial