Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Decision Making: Equality and Relational Operators - JavaScript(JS)

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Introduction to Scripting

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Decision Making: Equality and Relational Operators - JavaScript(JS)

This section introduces a version of JavaScript’s if statement that allows a program to make a decision based on the truth or falsity of a condition.

Decision Making: Equality and Relational Operators

 

This section introduces a version of JavaScript’s if statement that allows a program to make a decision based on the truth or falsity of a condition. If the condition is met (i.e., the condition is true), the statement in the body of the if statement is executed. If the condition is not met (i.e., the condition is false), the statement in the body of the if state


ment is not executed. We will see an example shortly. [Note: Other versions of the if state-ment are introduced in Chapter 7, JavaScript: Control Statements I.]

 

Conditions in if statements can be formed by using the equality operators and rela-tional operators summarized in Fig. 6.16. The relational operators all have the same level


of precedence and associate from left to right. The equality operators both have the same level of precedence, which is lower than the precedence of the relational operators. The equality operators also associate from left to right.

The script in Fig. 6.17 uses four if statements to display a time-sensitive greeting on a welcome page. The script obtains the local time from the user’s computer and converts it from 24-hour clock format (0–23) to a 12-hour clock format (0–11). Using this value, the script displays an appropriate greeting for the current time of day. The script and sample output are shown in Fig. 6.17.

 

Lines 12–14 declare the variables used in the script. Remember that variables may be declared in one declaration or in multiple declarations. If more than one variable is declared in a single declaration (as in this example), the names are separated by commas (,). This list of names is referred to as a comma-separated list. Once again, note the com-ment at the end of each line, indicating the purpose of each variable in the program. Also note that some of the variables are assigned a value in the declaration—JavaScript allows you to assign a value to a variable when the variable is declared.

      <?xml version = "1.0" encoding = "utf-8"?>

 

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

      <!-- Fig. 6.17: welcome6.html -->

 

      <!-- Using equality and relational operators. -->

 

      <html xmlns = "http://www.w3.org/1999/xhtml">

 

      <head>

 

      <title>Using Relational Operators</title>

 

        <script type = "text/javascript">

        <!--

 

var name; // string entered by the user

 

var       now = new Date();   //          current date and time

var       hour = now.getHours();       //          current hour (0-23)

                                   

        // read the name from the prompt box as a string

 

name = window.prompt( "Please enter your name" );

      // determine whether it is morning

 

if ( hour < 12 )

document.write( "<h1>Good Morning, " );

      // determine whether the time is PM

 

      if ( hour >= 12 )

{

// convert to a 12-hour clock

     hour = hour - 12; 

                  

// determine whether it is before 6 PM

     if ( hour < 6 )             

     document.write( "<h1>Good Afternoon, " );

                  

// determine whether it is after 6 PM

     if ( hour >= 6 )  

     document.write( "<h1>Good Evening, " );

} // end if

                  

document.writeln( name +

      ", welcome to JavaScript programming!</h1>" );

      // -->

 

      </script>

 

      </head>

 

      <body>

 

      <p>Click Refresh (or Reload) to run this script again.</p>

 

      </body>

 

</html>

 


Fig. 6.17 | Using equality and relational operators.

 

Line 13 sets the variable now to a new Date object, which contains information about the current local time. In Section 6.2, we introduced the document object, an object that encapsulates data pertaining to the current web page. Programmers may choose to use other objects to perform specific tasks or obtain particular pieces of information. Here, we use JavaScript’s built-in Date object to acquire the current local time. We create a new instance of an object by using the new operator followed by the type of the object, Date, and a pair of parentheses. Some objects require that arguments be placed in the parentheses to specify details about the object to be created. In this case, we leave the parentheses empty to create a default Date object containing information about the current date and time. After line 13 executes, the variable now refers to the new Date object. [Note: We did not need to use the new operator when we used the document and window objects because these objects always are created by the browser.] Line 14 sets the variable hour to an integer equal to the current hour (in a 24-hour clock format) returned by the Date object’s getHours method. Chapter 11 presents a more detailed discussion of the Date object’s attributes and methods, and of objects in general. As in the preceding example, the script uses window.prompt to allow the user to enter a name to display as part of the greeting (line 17).

 

To display the correct time-sensitive greeting, the script must determine whether the user is visiting the page during the morning, afternoon or evening. The first if statement (lines 20–21) compares the value of variable hour with 12. If hour is less than 12, then the user is visiting the page during the morning, and the statement at line 21 outputs the string "Good morning". If this condition is not met, line 21 is not executed. Line 24 determines whether hour is greater than or equal to 12. If hour is greater than or equal to 12, then the user is visiting the page in either the afternoon or the evening. Lines 25–36 execute to determine the appropriate greeting. If hour is less than 12, then the JavaScript interpreter does not execute these lines and continues to line 38.

 

The brace { in line 25 begins a block of statements (lines 27–35) that are all executed together if hour is greater than or equal to 12—to execute multiple statements inside an if construct, enclose them in curly braces. Line 27 subtracts 12 from hour, converting the current hour from a 24-hour clock format (0–23) to a 12-hour clock format (0–11). The if statement (line 30) determines whether hour is now less than 6. If it is, then the time is between noon and 6 PM, and line 31 outputs the beginning of an XHTML h1 element ("<h1>Good Afternoon, "). If hour is greater than or equal to 6, the time is between 6 PM and midnight, and the script outputs the greeting "Good Evening" (lines 34–35). The brace } in line 36 ends the block of statements associated with the if statement in line 24. Note that if statements can be nested, i.e., one if statement can be placed inside another if statement. The if statements that determine whether the user is visiting the page in the afternoon or the evening (lines 30–31 and lines 34–35) execute only if the script has already established that hour is greater than or equal to 12 (line 24). If the script has already determined the current time of day to be morning, these additional comparisons are not performed. (Chapter 7, JavaScript: Control Statements I, presents a more in-depth discus-sion of blocks and nested if statements.) Finally, lines 38–39 output the rest of the XHTML h1 element (the remaining part of the greeting), which does not depend on the time of day.

Note the indentation of the if statements throughout the program. Such indentation enhances program readability.

 

Note that there is no semicolon (;) at the end of the first line of each if statement. Including such a semicolon would result in a logic error at execution time. For example,

 

if ( hour < 12 ) ;

 

document.write( "<h1>Good Morning, " );

 

would actually be interpreted by JavaScript erroneously as

 

if ( hour < 12 )

 

;

 

document.write( "<h1>Good Morning, " );

 

where the semicolon on the line by itself—called the empty statement—is the statement to execute if the condition in the if statement is true. When the empty statement executes, no task is performed in the program. The program then continues with the next state-ment, which executes regardless of whether the condition is true or false. In this example, "<h1>Good Morning, " would be printed regardless of the time of day.

Note the use of spacing in lines 38–39 of Fig. 6.17. Remember that white-space char-acters, such as tabs, newlines and spaces, are normally ignored by the browser. So, state-ments may be split over several lines and may be spaced according to the programmer’s preferences without affecting the meaning of a program. However, it is incorrect to split identifiers and string literals. Ideally, statements should be kept small, but it is not always possible to do so.

The chart in Fig. 6.18 shows the precedence of the operators introduced in this chapter. The operators are shown from top to bottom in decreasing order of precedence. Note that all of these operators, with the exception of the assignment operator, =, associate from left to right. Addition is left associative, so an expression like x + y + z is evaluated as if it had been written as (x + y) + z. The assignment operator, =, associates from right to left, so an expression like x = y = 0 is evaluated as if it had been written as x = (y = 0), which first assigns the value 0 to variable y, then assigns the result of that assignment, 0, to x.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.