JavaScript and JScript Statements

[ LiB ]

JavaScript and JScript Statements

JavaScripts and JScripts consist of a series of statements. These statements are the programming instructions, or logic, that you write to tell the scripts what you want them to do.

Using Conditional Statements to Alter Script Flow

Conditional statements enable you to test for various conditions and take action based on the results of the test. Specifically, conditional statements execute when the tested condition proves to be true . Conditional statements include the if, if...else, and switch statements.

The if Statement

The if statement checks whether a logical condition is true; if it is, it then executes one or more statements. The basic syntax of the if statements is shown here:

 if (condition)   statement 

For example, the following pair of statements shows a simple if statement. The first line sets up a conditional test. If the test proves true (for example, if the counter variable is currently less than 10), the statement immediately following is executed. In this example, the current value of the variable counter is then incremented by 1.

 if (counter < 10)   counter++; 

There will be times when executing a single statement is just not enough. In this case, you can write your if statement using the following format:

 if (counter > 10) {  counter++;  window.alert("This is a test"); } 

The preceding example shows an if statement where the condition is followed immediately by the { sign and terminated with the } sign. Between the braces can be any number of script statements.

The following sample script uses the two types of if statements you just looked at plus a third variation:

 <HTML>   <HEAD>     <TITLE>Script 2.9 - Demonstration of if statements</TITLE>   </HEAD>   <BODY>      <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var accountStatus = open;  //assume all accounts are open by default       //Prompt the user for an account name       var accountName = window.prompt("Enter your account name:");       //Test whether the supplied account name equals Morganstern       if (accountName == "Morganstern")         document.write("The account number for this account is 12321. <BR>");       //Set accountStatus equal to warning if the account name equals Davidson       if (accountName == "Davidson") {         document.write("The account number for this account is 88844. <BR>");         accountStatus = "warning";       }       //Display one of two messages based on the value of accountStatus       if (accountStatus != "warning") {         document.write("You may accept new orders from this customer.");       }       else {         document.write("Do not accept new orders for this account.");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

This example starts by displaying a prompt dialog box asking the user to input the name of a business account using the window.prompt() method. Next , it executes three if statements, each of which compares the user's input against three separate criteria. Any conditional test that proves true results in some action. As you can see, the if statement enables you to create different logical flows based on user input.

The third if statement adds a new twist by adding an else statement. In the event that the if statement's conditional test proves true , the statements following the if statement are executed, and the else statement is skipped . But if the if statement proves false , the logic in the else statement is processed . The else statement enables you to provide an alternative course of action for any conditional test.

Figures 2.6 and 2.7 show the logical flow of the script when the user inputs the account name of Morganstern.

Figure 2.6. The window. prompt() method enables you to create a dialog box that gathers user input interactively.

graphic/02fig06.gif


Figure 2.7. Here is what happens when the user types in a valid business account name.

graphic/02fig07.gif


Before I move on, there is one final variation of the if statement I want to mention. This is the nested if statement . A nested if statement is a series of two or more if statements nested or embedded within one another. The following example shows a nested if that is two if statements deep. The second if statement is executed only if the first if statement proves true :

 if (accountStatus != "warning") {   if (accountNumber > 10000) {     document.write("You may accept new orders from this customer.");     }   else {     document.write("Invalid account number. Notify bank security.");   } } Else {   document.write("This Account has been marked with a warning!"); } 

The switch Statement

The switch statement evaluates a series of conditional tests or cases and executes additional statements based on whether the case proves true . The syntax of the switch statement is shown here:

 switch (expression) {   case label:     statements;   break;     .     .     .    case label:     statements;   break;   default:    statements; } 

The switch statement compares the result of the expression against the label for each case . The statements for the first case that proves true are executed. If no case proves true , the statements associated with the default statement are executed if the optional default statement was included.

The break statement at the end of each case is optional. Its purpose is to tell the script to exit the switch statement as soon as the statements in the first matching case are executed and to proceed with the next script statement following the switch statement. If you remove the optional break statements, the script will continue to examine each case and execute the statements of any case that matches the expression.

In the following example, the user is prompted to type the name of a business account. Starting with the first case statement, the script compares the value assigned to the accountName variable to the label assigned to the first case statement. If the condition proves true (that is, if there is a match), the statements for that case statement are executed, and the break at the end of the case statement tells the script to jump to the first statement after the switch statement, which in this example happens to be an if statement. If none of the case statements proves true , the statement associated with the default statement executes, stating that the account name the user typed is not registered. Figure 2.8 shows what this example looks like when it's executed.

Figure 2.8. The script flags Paterson as an invalid account name.

graphic/02fig08.gif


 <HTML>   <HEAD>     <TITLE>Script 2.10 - Demonstration of the switch statement</TITLE>   </HEAD>    <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var accountStatus = "None";       var accountName = window.prompt("Enter your account name:");       switch (accountName) {         case "Morganstern":           document.write("The account number for this account is 12321.");           accountStatus = "approved";           break;         case "Davidson":           document.write("The account number for this account is 88844.");           accountStatus = "warning";           break;         default:           document.write("The account is not registered in this system.");           accountStatus = "error";       }       if (accountStatus == "warning") {         document.write(accountStatus);         window.alert("Contact the on-duty supervisor");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Adding Comments for Clarity

Comment statements have no effect on the logical performance of the script. However, they can be used to make scripts easier to understand by providing you with a means of internally documenting your scripts. You can place a comment in your scripts in either of two ways. To place a single comment line within the body of your script, type // followed by your comment, as shown here:

 //This is an example of a script comment 

You can also add a comment at the end of script statements as demonstrated here.

 document.write("Hello World");  //Write a message to the current Window 

If one line isn't enough space for you to write out a complete comment, you may always add additional comments as demonstrated below.

 //The following statement writes a message in the currently open browser window //using the document object's write4() method. document.write("Hello World"); 

Alternatively, you may create multiline comments by placing them inside the /* and */ characters as demonstrated in the following example.

 /* The following statement writes a message in the currently open browser window using the document object's write4() method. */ document.write("Hello World"); 

Comments are not always for other people; they are for you as well. For example, you might have a large script, several pages long, that allows customers to fill in a form and place orders for some type of product. If the tax rate changes, you'll have to find the portion of the script that does this calculation and change it. If you had added a comment that identifies the line of code where the tax calculation is performed as demonstrated below, it would make it easier to modify the script years later.

 //Compute the amount of tax to apply to the order totalOrder = totalOrder + (totalOrder * .05); 

The following script provides an example of how you might document your own scripts:

 <HTML>   <HEAD>     <TITLE>Script 2.11 - Comment Example</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       //Define a variable representing the cost of a customer order        var totalOrder = 100;       //Compute the amount of tax to apply to the order       totalOrder = totalOrder + (totalOrder * .05);  //Tax rate = 5%       /*The following statement simply demonstrates the use of the document statement to write       a message on the current browser window.*/       document.write(totalOrder);     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

NOTE

Another technique for making scripts easier to read is the insertion of blank lines between different groups of statements.

Declaring and Assigning Data to Variables

We already examined variable declaration and assignment statements at the beginning of this session. Most assignments are performed using the equal sign (=) , but you can use any of the assignment operators listed in Table 2.3.

Optimizing Code with Looping Logic

A loop is a series of statements that executes repeatedly, allowing you to perform iterative operations within your script. JavaScript and JScript statements that support looping logic include the for, while, do...while, label, break, and continue statements. The nice thing about loops is that they enable you to write just a few line of code and then to execute them repeatedly, making your scripts easier to write and maintain.

The for Statement

The for statement executes until a condition becomes false and uses a variable to control the number of times the loop executes. The for loop is comprised of three parts : a starting expression, a test condition, and an increment statement. The syntax of the for statement is shown here:

 for (expression; condition; increment) {   statements; } 

For example, the statement for (i=0; i<5; i++) establishes a for loop that has an initial count of 0, that runs as long as i is less than 5, and that increments the value of i by one upon each iteration. All the statements within the starting and ending brackets are executed with each execution of the for loop.

The following example shows how the for statement can be used to set up a loop that iterates five times. When the script begins to execute, the value of i is 0. Each time the loop executes, the value of i is incremented by 1 (in the i++ clause). Although this example displays just five lines of text that show the value of i as it grows, I think you can see that it can be easily modified to do just about anything, such as repeatedly prompting the user for input and iteratively processing that input.

 <HTML>   <HEAD>     <TITLE>Script 2.12 - Demonstration of a for loop</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements        for (i=0; i<5; i++) {         document.write("Watch as the variable grows with each iteration: ",i,"<BR>");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Figure 2.9 shows the result of loading the previous example. If you run this script yourself, you should take note just how quickly the scripts executes.

Figure 2.9. An example of using a for loop to perform iterative processes

graphic/02fig09.gif


The while Statement

The while statement executes a loop as long as a condition is true . The syntax of the while statement is shown here:

 while (condition) {  statements;  } 

For example, you might write a while loop that looks like this:

 while (counter > 0) {   counter++;   document.write("counter = ", counter , "<BR>"); } 

In the next example, I set up a loop that runs as long as the value assigned to a variable named counter is greater than 0. As soon as counter becomes 0 or less, the loop terminates. To control the termination of the loop, I decremented the value of counter by 1 each time through the loop. When working with while loops, be sure that you set them up so that they will properly break out of the loop; otherwise , they will run forever, leaving the user no option other than to close the HTML page or terminate the execution of your JScript.

This is because the while loop is designed to iterate for as long as the tested condition remains true , as demonstrated in the following example.

 <HTML>   <HEAD>     <TITLE>Script 2.13 - Demonstration of the while statement</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var counter = 10;       document.write("<B>Watch me count backwards!</B><BR>");       while (counter > 0) {         counter;          document.write("counter = ", counter , "<BR>");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Figure 2.10 shows the results of loading this example using Internet Explorer.

Figure 2.10. An example of looping backward using a while loop

graphic/02fig10.gif


The do while Statement

The do while statement executes a loop until a condition becomes false . The syntax of the do while statement is outlined below:

 do {   statements; } while (condition) 

The difference between the do while loop and the while loop is that the do while loop always executes at least once. This is because the condition is checked at the end of the first execution of the loop instead of at the beginning. However, you can use either style to achieve the same end, as demonstrated in the next example.

 <HTML>   <HEAD>     <TITLE>Script 2.14 - Demonstration of the do...while statement</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var counter = 10;       document.write("<B>Watch me count backwards!</B><BR>");       do {         counter;         document.write("counter = ", counter , "<BR>");       } while (counter > 0)     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

The results of running this script are exactly the same as those that were displayed in Figure 2.11.

Figure 2.11. Using the for in statement to loop through the screen object's properties

graphic/02fig11.gif


NOTE

You may have noticed my use of commas in the document.write() statement located in the preceding example. In this context, commas are used to separate a list of arguments used by the document.write() statement.For example,in document . write("counter = ", counter , "<BR>");, three arguments are passed. The first argument is a text message surrounded by double quotes, the second argument is a variable named counter whose value will be displayed when the statement is executed, and the final argument is a HTML line break tag.

The label Statement

The label statement lets you specify a reference point in your script. Typically, the label statement is associated with loops. A label statement can be referenced by either the break or continue statement. The syntax of the label statement is shown here:

  label:   statements;  

In the following example, I have created a label called CounterLoop . When the script executes the first time, the label statement is ignored. Within the while loop, I set up a test that checks to see whether the value of counter is equal to 5. If it is, the script executes the continue statement, which tells the script to skip the rest of the statements in the while statement and continue with the next execution of the loop.

 <HTML>   <HEAD>     <TITLE>Script 2.15 - Demonstration of the label statement </TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var counter = 10;        document.write("<B>Watch me count backwards!</B><BR>");       CounterLoop:       while (counter > 0) {         counter;         if (counter == 5) continue CounterLoop;         document.write("counter = ", counter , "<BR>");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

When you load this script, you will see that the continue statement has the effect of skipping the display of the fifth statement.

The break Statement

The break statement lets you terminate a label, switch, or loop. The script then continues processing with the statement that follows the label, switch , or loop statement that was broken out of.

The following example shows how to use the break statement to terminate the execution of a while loop. In this case, the break statement terminates the loop when the value of counter becomes equal to 5. Because there are no other statements following the while loop, script execution stops when it processes the break statement.

 <HTML>   <HEAD>     <TITLE>Script 2.16 - Demonstration of the break statement</TITLE>   </HEAD>    <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var counter = 10;       document.write("<B>Watch me count backwards!</B><BR>");       while (counter > 0) {         counter;         document.write("counter = ", counter , "<BR>");         if (counter == 5) break;       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

The continue Statement

The continue statement is similar to the break statement. However, instead of terminating the execution of the loop, it merely terminates the current iteration of the loop.

The following example demonstrates how the continue statement can be used to terminate a given iteration of a loop. In this example, the loop examines four different cases as part of a switch statement. The result is that the iteration of the loop that occurs when the value assigned to the counter variable is equal to 8, 6, 4, or 2 is skipped, but processing of the loop does not terminate as would be the case when using a break statement. Instead, the loop simply continues with the next iteration.

 <HTML>   <HEAD>     <TITLE>Script 2.17 - Demonstration of the continue statement</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var counter = 10;       document.write("<B>Watch me count backwards!</B><BR>");       CounterLoop:       while (counter > 0) {         counter;         switch (counter) {           case 8:             continue CounterLoop;           case 6:             continue CounterLoop;           case 4:             continue CounterLoop;           case 2:             continue CounterLoop;         }         document.write("counter = ", counter , "<BR>");       }      // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Manipulating Objects

As I have already stated, JavaScript and JScript enable you to create scripts that work with objects. You can think of objects as being similar to variables except that objects can contain multiple values known as its properties. Objects also can contain built-in functions, which are collections of predefined script statements that are designed to work with the object and its data. Examples of browser objects include browser windows and form elements. Examples of WSH objects include printers and drives .

There are a number of JavaScript and JScript statements that provide you with the ability to manipulate properties associated with objects. These statements include the for in and with statements. The for in statement enables you to access all the properties for a specified object, and the with statement provides easy access to specific object properties and methods .

The for in Statement

The for in statement is used to iterate through all the properties belonging to a specified object. The syntax of the for in statement is listed below:

 for (  variable  in  object  ) {  statements;  } 

This statement works by creating a variable that is used to iterate through all of an object's properties. The following example shows how to loop through all the properties belonging to the navigator object. The navigator object contains information about the type of browser being used to view the HTML page containing the JavaScript.

 <HTML>   <HEAD>     <TITLE>Script 2.18 - Demonstration of the forin statement </TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       for (i in navigator) {           document.write(i,"<BR>");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Figure 2.11 shows the result of loading the preceding page using Internet Explorer. By modifying this example, you can easily view all the properties for any object. However, I'd recommend that you save yourself the trouble of modifying this example and refer to Appendix A, "A Brief JavaScript and JScript Object Reference," to get information about the various properties of any object.

The with Statement

The with statement is a convenient way of saving a few keystrokes when writing your scripts. It enables you to set a default object for a group of statements. The syntax of the with statement is listed below.

 with (  object  ) {  statements;  } 

The following example shows how you can use the with statement to set the document object as the default object and then apply all the statements contained within the opening and closing braces to that object. As you can see, by using this shortcut statement, I was able to type write() in place of document.write() . Although this did not save me much work in this example, it could certainly save a lot of time in situations where you need to work a lot with a given object.

 <HTML>   <HEAD>     <TITLE>Script 2.19 - Demonstration of the with statement </TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       with (document) {          write("The with statement saved me a few keystrokes. <BR>");         write("Its use is purely discretionary!");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

[ LiB ]


Learn JavaScript In a Weekend
Learn JavaScript In a Weekend, Second Edition
ISBN: 159200086X
EAN: 2147483647
Year: 2003
Pages: 84

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net