JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.00

Conditional "if" Statement Examples

This section provides a JavaScript tutorial example showing different types of 'if' statements.

To help you understand how "if" statements work, I wrote the following the JavaScript tutorial example, If_Statements.html:

<html>
<!-- If_Statements.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>If Statements</title></head>
<body>
<pre>
<script type="text/javascript">
   // Single-statement "if"
   document.write('\n');
   var is_january = true;
   if (is_january) document.write("Happy New Year!\n");

   // Multi-statement "if"
   document.write('\n');
   var is_log_on = true;
   if (is_log_on) {
      document.write("Open the log file.\n");
      document.write("Write the log message.\n");
      document.write("Close the log file.\n");
   }
   
   // "if ... else" statement
   document.write('\n');
   var is_admin = false;
   if (is_admin) {
      document.write("Display the delete button.\n");
      document.write("Display the edit button.\n");
   } else {
      document.write("Display the view button.\n");
   }
   
   // "if ... else if" statement
   document.write('\n');
   var week_day = 4;
   var open_hours;
   if (week_day == 0) {
      open_hours = "closed";
   } else if (week_day >= 1 && week_day <= 5) {
      open_hours = "open from 9:00am to 9:00pm";
   } else if (week_day == 6) { 
      open_hours = "open from 9:00am to 5:00pm";
   } else {
      open_hours = "undefined";
   }
   document.write("The library is " + open_hours + ".\n");
</script>
</pre>
</body>
</html>

The output of this sample JavaScript is:


Happy New Year!

Open the log file.
Write the log message.
Close the log file.

Display the view button.

The library is open from 9:00am to 9:00pm.

Sections in This Chapter

What Is a Statement?

Conditional "if" Statements

Conditional "if" Statement Examples

"switch ... case" Statements

"switch ... case" Statement Example

"for" Loop Statements

"for" Loop Statement Example

"while" Loop Statements

"while" Loop Statement Example

Dr. Herong Yang, updated in 2008
Conditional "if" Statement Examples