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:

<!-- If_Statements.html
   Copyright (c) 2002 All Rights Reserved.
<head><title>If Statements</title></head>
<script type="text/javascript">
   // Single-statement "if"
   var is_january = true;
   if (is_january) document.write("Happy New Year!\n");

   // Multi-statement "if"
   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
   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
   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");

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.

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

Flow Control Statements

 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

 Creating, Accessing, and Manipulating Arrays

 Defining and Calling Functions

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 AJAX (Asynchronous JavaScript And XML)


 Full Version in PDF/EPUB