Chapter 15 Programming Using JavaScript
15.1 Introduction to JavaScriptJavaScript is the most commonly used scripting language because it is supported by most browsers. JavaScript lives and works within Web pages on the World Wide Web. The original purpose of the World Wide Web was locating and displaying information. Once the Web grew beyond a small academic and scientific community, people began to recognize that greater interactivity would make the Web more useful. JavaScript brings HTML to life and makes Web pages dynamic. Instead of HTML documents being static, JavaScript can turn them into applications, such as games or order forms. You can use JavaScript to change the contents of a Web page after it has been rendered by a browser, to interact with a user through forms and controls, to create visual effects such as animation, and to control the Web browser window itself. None of these things was possible before the creation of JavaScript. JavaScript is a cross-platform scripting language. The term scripting language refers to programming languages that are executed by an interpreter from within a Web browser. Many people think that JavaScript is a simplified version of the Java programming language. They are, however, entirely different languages. Java is a complied, object-oriented programming language that was created by Sun Microsystems and is considerably more difficult to master than JavaScript. JavaScript is an interpreted scripting language that was created by Netscape. Although Java is often used to create programs that can run from a Web page, Java programs are external programs that execute independently of a browser. In contrast, JavaScript programs run within a Web page and control the browser. Like HTML, JavaScript will work on all platforms. JavaScript allows you to enhance the functionality of your Web pages by embedding applications directly into your HTML. JavaScript is an object-based language with strong support for proper software engineering techniques. It provides the solid foundation of programming principles. It presents an introduction to the fundamentals of computer programming including control structures, functions, arrays, strings, objects, etc. The simplicity of JavaScript and its combination with the HTML motivate this course to use the programming language to promote your programming knowledge and skill. The major purpose of learning programming in this course is to let you have direct experience in programming environment. When a browser receives a Web page from a Web server, the browser interprets the HTML code and renders the Web page. A pair of script tags separates script from HTML code. The script tag <script> identifies the beginning of a script, and </script> identifies the end of the script. If a script statement is found outside of these script tags, the browser displays an error message, and the Web page is not displayed correctly. When a Web browser identifies a script, the browser passes the script to the script interpreter or script engine, a program that executes the script as the page is being loaded. After the script is executed, the Web browser continues to interpret HTML code until it encounters another pair of script tags. The Web page can have many scripts interspersed within HTML code, as long as script tags delimit each script. The syntax used is as follows: <script language = "language-Name">
Several scripting languages are available to create client-side scripts. The most common script languages are JavaScript, Jscript, and VBScript. You can identify the script language with the language attribute in <script>. If the language attribute is absent, the default client script language is used. The default script for most browsers is JavaScript. Because the end user can change the default language for scripting, you should always use the language attribute. For example, to specify JavaScript, write <script language = "JavaScript"> JavaScript uses notations that may appear strange to non-programmers. We begin by considering a simple script that writes the text "Hello World" to the HTML document. Figure 15-1 shows the script and Figure 15-2 displays its output.
This program illustrates several important features of implementing a JavaScript in an HTML document. You can
create the script source file with a simple text editor such as Notepad. Scripts can be placed in the head or body
section of the Web pages. If you place a script in the head section of the Web page, the script engine interprets
that script before it interprets scripts located in the body section. When a script is at the end of the Web page,
the Web page loads faster, and users can continue viewing the page while the script engine interprets the script.
This example shows placing the same script in both head and body sections of the Web page. The scripts are enclosed
in the <SCRIPT>...</SCRIPT> tag pair. The tag pair indicates to the browser that the statements contained
between the opening and closing tag is a script. Individual lines in a programming language are called
statements.
Every statement should end with a semicolon (;). The In the example of Figure 16-1, the statement document.write("<H1>Hello World</H1>"); instructs the browser’s JavaScript interpreter to perform an action, namely to display in the Web page the string of characters contained between the double quotation (") marks. A string is sometimes called a character string, a message or a string literal. We refer to characters between double quotation marks generically as strings. Whitespace characters in strings are not ignored by the browser. This statement uses the browser’s document object, which represents the HTML document currently being displayed in the browser. An object is programming code and data that can be treated as an individual unit or component. Groups of related statements associated with an object are called methods. JavaScript treats many things as objects. The browser contains a complete set of objects that allow script programmers to access and manipulate every element of an HTML document. One of the most commonly used objects in JavaScript programming is the document object. The document object represents the content of a browser’s window. Any text, graphics, or other information displayed in a Web page is part of the document object. One of the most common uses of the document object is to add new text to a Web page. You create new text on a Web page with the write() method of the document object. To execute an object’s method, you append the method to the object with a period, and include any required arguments or parameters between the method’s parentheses. An argument is any type of information that can be passed to a method. The write() method of the document object require a text string as an argument. The text string that is passed as an argument to the write() method of the document object is the text that the document object uses to create new text on a Web page. In our example, the statement document.write("<H1>Hello World</H1>"); writes the text Hello World to the HTML document. When you want to include a quoted string within a string, you surround the quoted text with single quotation marks. For example, the statement document.write("<H1>Hello 'Beautiful' World</H1>"); writes the text Hello ‘Beautiful’ World to the HTML document. If the string contains HTML elements, the browser interprets these elements and renders them on the screen. In this example, the browser displays the phrase Hello World as an H1-level HTML head, because the phrase is enclosed in an H1 element. When you create a program, it is considered good programming practice to add comments to your code. The two slashes // before the text in JavaScript create a single-line comment. Single ling-comments can appear at the end of a line of code, or they can exist on an entire line by themselves. In our example, //script in body section is a single-line comment. Comments do not cause the browser to perform any action when the script is interpreted; rather, comments are ignored by the JavaScript interpreter. JavaScript is case sensitive. Not using the proper uppercase and lowercase letters is a syntax error. A syntax error occurs when the script engine cannot recognize a statement. The engine normally issues an error message to help the programmer locate and fix the incorrect statement. When the engine reports a syntax error, the error may not be on the line indicated by the error messages. First, check the line where the error was reported. If that line does not contain error, check the preceding several lines in the script. 15.2 Window Dialog Boxes Sometimes it is useful to display information in windows called dialog boxes that "pop up" on the screen to grab the user’s attention. These predefined dialog boxes are used to obtain information from the user, or to provide the user with information. The three window methods that create dialog boxes are the prompt, alert, and confirm methods. The syntax and an example of each method are listed in Figure 15-3.
The prompt method creates the prompt dialog box, which is used to obtain information from the user. The prompt dialog box uses a string, which can be used to indicate to the user what type of information to enter. The information the user enters in the prompt dialog box can then be retrieved. The prompt dialog box contains the prompt message, default string to be placed inside the text box, an OK button, and a Cancel button. The alert method creates an alert dialog box, which is often used on a form to provide a simple message to the user, such as "You forgot to enter your last name." The alert box contains a single message and an OK button. The confirm method is often used to require the user to accept or reject some condition. The confirm box contains the message, an OK button, and a Cancel button. Clicking the OK button would return true, and the action would be taken. The user could click the Cancel button, which would return false, and then the script wouldn’t take the action.
Figure 15-4 shows an example that uses prompt dialog box to allow a user to enter two integers. Then the program computes the sum of these values and displays the result. The statement in the example firstNumber = window.prompt("Enter first number", "0"); allows the user to enter a string representing the first of the two integers that will be added. The first argument "Enter first number" indicates to the user what to do in the text field. This message is called a prompt because it directs the user to take a specific action. The optional second argument is the default string to display in the text field. If the second argument is not supplied, the text field does not contain a default value. The user types characters in the text field, then clicks the OK button to return the string to the program. Technically, the user can type anything in the text field of the prompt dialog. For this program, if the user either types a non-integer value or clicks the Cancel button, a run-time logic error will occur and the sum of the two values will appear in the HTML document as NaN (Not a Number). The result of the call to widow.prompt is given to variable The statement number1 = parseInt(firstNumber); converts the string entered by the user to integer value that can be used in a calculation. Function The assignment statement sum = number1 + number2; calculates the sum of the variables Finally, the statement document.write("The sum is " + sum); displays the result of the addition using document.write. The expression "The sum is " + sum uses the string concatenation operator (+) to "add" a string (the literal "The sum is ") and sum (the variable containing the integer result of the addition). The string concatenation operator enables a string and a value of another data type (including another string) to be concatenated. The result of this operation is a new string. Figure 15-5 shows the two prompt dialog boxes and the result of the program.
15.3 Variables, Expressions and Operators Variables The statements in Figure 15-4
var firstNumber, secondNumber, //two string entered by user
are a declaration. The keyword One of the most important aspects of programming is the ability to store and manipulate values in computer memory
locations. The values stored in computer memory locations are called variables. Data contained in a specific
variable often change. For example, the variable JavaScript uses the reserved keyword
When you use the reserved word var variable_name = value; The equal sign in a variable declaration assigns a value to the variable. This use is different from the standard use of the equal sign in an algebraic formula. The value you assign a variable can be a string or a numeric value. You can declare multiple variables in the same statement using a single var firstVar = "text", secondVar = 2.5, thirdVar; Notice in this example, although you can assign a value when a variable is declared, you are not required to do so,
like the variable The name you assign to a variable is an identifier. JavaScript does not allow you to use a number as the first character
in an identifier, so that it can easily distinguish between an identifier and a literal value. There are some rules and
conventions you need to follow when naming a variable. Reserved words cannot be used for variable names, and you cannot use
spaces within a variable name. Common practice is to use an underscore (_) character to separate individual words within a
variable name, as in Variable names, like other JavaScript code, are case-sensitive. Therefore, the variable name When you use a variable in a JavaScript program, particularly a complex program, you need to be aware of the variable’s scope. The part of a script in which a variable name can be used is known as the variable scope. Data Types Variables can contain many different kinds of values—for example, the time, a dollar amount, or a person’s name. The values or data contained in JavaScript variables can be classified by categories know as data types. A data type is the specific category of information that a variable contains. A variable’s data type determines how its value is stored. Data types that can be assigned only a single value are called primitive types. JavaScript supports five primitive data types: string, integer numbers, floating-point numbers, Boolean values, and the null value. Figure 15-7 lists the primitive data types.
A text string contains zero or more characters surrounded by double or single quotation marks. You can use text strings as literal values or assign them to a variable. Variable can be assigned a zero-length string value called an empty string. For example,
assigns an empty string to
the variable
Numeric data types are an important part of any programming language, and are particularly useful when doing arithmetic calculations. An integer is a positive or negative number with no decimal place. Integer values in JavaScript can range from –9007199254740992 (-253) to 9007199254740992(253). A floating-point number contains decimal places or is written using exponential notation. The numbers –6.17, 3.52 and 2.0e7 are examples of floating-point number. Floating-point values in JavaScript range from ±1.7976931348623157×10308 to ±5×10-324. A
Boolean value is a logical of true or false. Boolean value are most often
used for decision making and comparing data. In JavaScript programming, you can
only use the words The null value is a data
type as well as a value that can be assigned to a variable. Assigning the value
Many programming languages require that you declare the type of data that a variable contains. Programming languages that require you to declare the data types are called strongly-typed programming languages. JavaScript does not require variables to have a type before they can be used in a program. A variable in JavaScript can contain a value of any data type, and in many situations JavaScript automatically converts between values of different types for you. For this reason, JavaScript is referred to as a loosely-typed programming language. When a variable is declared in
JavaScript but is not given a value, that variable has an undefined
value. Attempting to use the value of such a variable is normally a logic error.
To indicate that a variable does not contain a value, you can assign the value
Expressions Variables and data become most useful when you use them in an expression. An expression is a combination of literal values, variables, operators, and other expressions that can be evaluated by the JavaScript interpreter to produce a result. Figure 15-10 shows the literal values and variables that can be recognized by the JavaScript interpreter as expressions. You can use operands and operators to create more complex expressions. Operands are literals and variables contained in an expression. Operators are symbols used in expressions to manipulate operands. For example, the statement lastName = "Davis";
is an expression that results in the value Arithmetic Operators Many script perform arithmetic calculations. The arithmetic operators are summarized in Figure 15-11. Notice that JavaScript provides the modulus operator, %, which yields the remainder after division. Thus, 23%7 yields 2. The modulus operator has many interesting applications such as determining whether one number is a multiple of another. There is no arithmetic operator for exponentiation in JavaScript. JavaScript applies the operators in arithmetic expressions in the same order as the rules of operator precedence followed in algebra.
JavaScript arithmetic operators are binary or unary. A binary operator
requires an operand before the operator
and an operand after the operator. The addition sign in the statement
When the increment or decrement operator is used as a prefix operator, the value of the operand is returned after
it is increased or decreased by a value of one. For example, in the following statements, the var newCount, count = 10;
newCount variable is assigned a value of 11. By contrast, when you use the increment or decrement
operator as a postfix operator, the value of the operand is returned before it is increased or decreased by a value of one.
For example, the postfix increment operator returns a value before adding one to the count variable,
and the newCount variable is assigned a value of 10 in the following statements:
var newCount, count = 10;
var x = 1000;
the variable x is initially assigned a value of positive 1000; then x is changed to -1000 using the negation unary operator. Assignment Operators Assignment operators are used for assigning a value to a variable. The equal sign (=) is the most common assignment operator. JavaScript also includes other assignment operators. These additional assignment operators perform mathematical calculations on variables and literal values in an expression, then assign a new value to the left operand. Figure 15-12 lists the common JavaScript assignment operators. Figure 15-13 shows code examples of the different assignment operators. The result of the program is displayed in Figure 15-14.
Comparison Operators Comparison operators are used to compare two operands for equality and to determine if one numeric value is greater than another. A Boolean value of true or false is returned after two operands are compared. Figure 15-15 lists the JavaScript comparison operators.
The comparison operators can be applied to both numbers and string. The number a is said to be less than the number b if a lies to the left of b on the number line. For instance, 2 < 5, -5 < -2, and 0 < 3.75. The string a is said to be less than the string b if a precedes b alphabetically when using the ASCII (or ANSI) table to alphabetize their values. For instance, "cat" < "dog", "cart" < "cat" and "cat" < "catalog". When one operand is a number and the other is a string, the JavaScript interpreter attempts to convert the string value to a number. If the string value cannot be converted to a number, a value of false is returned. Figure 15-16 shows a code example using comparison operators. In this example, the statement returnValue = a == b;
campares a and b, and then assigns value true to
Logical Operators
Programming situations often require more complex than simple conditions as (2 < n) && (n < 5)
The condition
Thus logical operators are used to form more complex conditions by combining simple conditions. The three main logical
operators are && (logical AND), || (logical OR) and ! (logical NOT). If condition1 && condition2
is true if both condition1 || condition2
is true if either !condition1
is true if
String Operators Two strings can be combined to form a new string consisting of the strings joined together. The joining operation is called concatenation and accomplished by using string operators +. The following code combines a string variable and a literal string, and assigns the new value to another variable: var firstString = "Current address: ";
The combined value of the Note that the same symbol - a plus sign - serves as the concatenation operator and the addition operator. When used with numbers or variables containing numbers, expressions using the plus sign will return the sum of the two numbers. However, if you use the plus sign with a string value and a number value, the string value and the number value will be combined into a new string value, as in the following example: var theString = "The legal voting age in U.S. is ";
The string The legal voting age in U.S. is 18 is assigned to the Operator Precedence When writing expressions in JavaScript, you need to be aware of the precedence of an operator. Operator precedence is the order of priority in which operations in an expression are evaluated. Figure 16-20 shows the rules of operator precedence.
15.4 Algorithm FormulationBefore you write a program to solve a particular problem, it is essential to have a thorough understanding of the problem and a carefully planned approach to solving the problem. When you are writing a problem, it is equally essential to understand the types of building blocks that are available and to employ proven program construction principles. Let us work thorough a complete problem to illustrate how algorithms are development, using top-down, stepwise refinement technique. Consider the following problem: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. The grades are integers in the range 0 to 100. We approach the class-averaging program with a technique called top-down, stepwise refinement, a technique that is essential to the development of well-structure algorithms. We begin with a pseudocode representation of the top:
The top is a single statement that conveys the overall purpose of the program. As such, the top is, in effect, a complete representation of a program. However, the top rarely conveys a sufficient amount of detail from which to write the JavaScript algorithm. So, we now begin the refinement process. We divide the top into a series of smaller tasks and list these in the order in which they need to be performed, creating the following first refinement: Initialize variables Input, sum up and count the exam grades Calculate and print the class average Here, only the sequence structure has been used - the steps listed are to be executed in order, one after the other. To proceed to the next level of refinement, we commit to specific variables. We need a running total of the numbers, a count of how many numbers have been processed, a variable to receive the string representation of each grade as it is input, a variable to store the value of the grade after it is converted to an integer and a variable to hold the calculated average. Thus, the pseudocode statement
may be refined as follows: Declare grade, gradeCounter, total, average, and gradeValue Initialize total to zero Initialize gradeCounter to zero Notice that only the variables
The pseudocode statement
requires a loop that successively inputs each grade. Because we do not know how many grades are to be processed, we will use sentinel-controlled repetition. The sentinel-controlled repetition uses a special value called a sentinel value (also called a dummy value or a flag value) to indicate “end of data entry.” The user at the keyboard will type legitimate grades in one at a time. After the last legitimate grade is typed, the user will type the sentinel value. The program will test for the sentinel value after each grade is input and will terminate the loop when the sentinel value is entered by the user. The second refinement of the preceding pseudocode statement is then Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) The pseudocode statement
may be refined as follows: If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “No grades were entered” Notice that we are testing for the possibility of division by zero - a logic error that, if undetected, would cause the program to produce invalid output. The complete second refinement of the pseudocode algorithm for the class-average problem is shown in Figure 15-21. This algorithm was developed after only two levels of refinement. Sometimes more levels are necessary. Each refinement, as well as the top itself, is a complete specification of the algorithm; only the level of detail varies. The JavaScript program is shown in Figure 15-21. Figure 15-22 shows the result of the program. Although the script reads only integers, the averaging calculation in the program produces a floating-point number. If the user enters a string containing a floating-point numeric value, the parseInt simply truncates the floating-point part. For example, the string “25.63” results in the integer 25 and the string “-123.45” results in the integer –123. If the string passed to parseInt is not a numeric value, parseInt returns NaN (not a number). JavaScript actually represents all numbers as floating-point numbers in memory. Floating-point numbers often develop through division, as shown in this example. The sample result in this example is 76.33333....., with the sequence of 3s repeating infinitely. The computer allocates only a fixed amount of space to hold such a value, so the stored floating-point value can only be an approximation.
15.5 Selection Control Structure Control Structure Normally, the statements in a program are executed in their physical order. The first statement is executed, then the second, and so on until all of the statements have been executed. The physical order is the order in which the statements appear in a program. However, what if we want the computer to execute the statements in some other order? The order in which we want the statements to be executed is called the logical order. We must be able to specify that the next statement to be executed may be other than the next one in sequence. This is called transfer of control. Structured programming utilizes control structures to control the flow of execution. JavaScript control structures enable us to combine individual instructions into a single logical unit with one entry point and one exit point. We then can write a program as a sequence of control structures rather than as a sequence of individual instructions. In many applications, the next statement to be executed will depend on the result of a decision or a comparison that the program must make. For example, a payroll program might need to decide if an employee worked overtime. Assuming a 40-hour workweek, the program can make that determination by comparing the number of hours the employee worked with the number 40. Based on the result of that comparison, the program will then select either an instruction that computes regular pay or an instruction that computes overtime pay. Statements in a JavaScript program can be organized into three kinds of control structures to control execution flow: sequence structure, selection structure, and repetition structure. The sequence structure processes the program statements one after another, in the order in which they appeared in the program. This section will discuss three types of selection control structures, and next section will discuss the four types of repetition control structures. Each program is formed by combining as many of each type control structure as is appropriate for the algorithm the program implements. You use the selection structure, also called the decision structure, when you want a program to make a decision or comparison and then, based on the result of the decision or comparison, to select one of alternative courses of action. JavaScript provides three types of selection structures: if, if/else, and switch structures. The if Selection Structure
A selection structure is used to choose among alternative courses of action in a program. The if structure is called the single-selection structure. This structure performs an action if a condition is true or skips the action if the condition is false. The syntax of the if statement is if (condition)
If condition is true the program will take action; if the condition is false, the action is ignored. Execution continues with the statement after the if block. The action consists of one or more script statements. For example, suppose the passing grade on an exam is 60. The flowchart and JavaScript code for this example are illustrated in Figure 15-23. This flowchart contains the most important flowcharting symbol - the diamond symbol (decision symbol) that indicates that a decision is to be made. The decision symbol contains an expression, such as a condition, that can be either true or false. We will soon learn that the flowcharts for the remaining control structures also contain (besides circle symbols and flowlines) only rectangle symbols to indicate the action to be performed and diamond symbols to indicate decisions to be made. This is the action/decision model of programming. Note that the if structure is a single-entry/single-exit structure. Single-entry/single-exit control structures make it easy to build programs - the control structures are attached to one another by connecting the exit point of one control structure to the entry point of the next. This process is similar to the way a child stacks building blocks, so we call this control-structure stacking. We will learn that there is only one other way control structures may be connected—control-structure nesting. Thus, algorithms in JavaScript are constructed from only eight types of control structures combined in only two ways. The programmer’s task, then, is to assemble a program from as many of each type of control structure as the algorithm demands, combining those control structures in only two possible ways, and then filling in the actions and decisions in a manner appropriate for the algorithm. The if/else Selection Structure The if/else selection structure allows a program to decide on a course of action based on whether a certain condition is true or false. The syntax of the if/else statement is: if (condition)
The program takes action1 if condition is true and takes actions2 if condition is false. This selection structure is called the double-selection structure because it selects between two different actions. After an action is taken, execution continues with the statement after the if/else block. Figure 15-24 illustrates the flowchart and code of the double-selection structure for the grade example.
Note that the body of the code follows indentation convention. Consistently applying reasonable indentation conventions throughout your programs improves program readability. JavaScript also provides an operator called the conditional operator (?:) that is closely related to the if/else structure. The operator ?: is JavaScript’s only ternary operator—it takes three operands. The operands together with the ?: form a conditional expression. The first operand is a Boolean expression, the second is the value for the conditional expression if the condition evaluates to true and the third is the value for the conditional expression if the condition evaluates to false. For example, the statement document.write(grade >= 60 ? “Pass” : “Fail”); contains a conditional expression that evaluates to the string Pass if the condition grade >= 60 is true and evaluates to the string Fail if the condition is false. Thus, this statement with the conditional operator performs essentially the same operation as the preceding if/else statement. The precedence of the conditional operator is low, so the entire conditional expression is normally placed in parentheses. Nested if/else structures test for multiple cases by placing if/else structure inside structures. In general, any problem that involves more than two alternative courses of action can be coded using a nested if/else structure. The nested if/else structure is called the multiple-selection structure because it selects among many different actions. For example, to assign a grade to a student given his/her exam score, we could use a nested if/else structure: if (grade >= 90)
It is important to note that the JavaScript interpreter always associates an else with the previous if, unless told to do otherwise by placing braces ({}). This is referred to as the dangling-else problem. For example, if (x > 5)
appears to indicate with its indentation that if x is greater than 5, the if structure in its body determines whether y is also greater than 5. If so the string x and y are > 5 is output. Otherwise, it appears that if x is not greater than 5, the else part of the if/else structure output the string x is <= 5. Beware! The preceding nested if/else structure does not execute as it appears. The interpreter actually interprets the preceding structure as if (x > 5)
in which the body of the first if structure is an if/else structure. This structure tests whether x is greater than 5. If so, execution continues by testing whether y is also greater than 5. If the second condition is true, the proper string, x and y are > 5, is displayed. However, if the second condition is false, the string x is <= 5 is displayed, even though we know x is greater than 5. To force the preceding nested if structure to execute as it was originally intended, the structure must be written as follows: if (x > 5)
The braces ({}) indicate to the interpreter that the second if structure is in the body of the first if structure and that the else is matched with the first if structure. The if selection structure normally expects only one statement in its body. To include several statements in the body of an if, enclose the statements in braces ({}). A set of statements contained within a pair of braces is called a compound statement. For example, if (grade >= 60)
indicates that if grade is less than 60, the program executes both statements in the body of the else. In this case, braces are important. Without the braces, the statement document.write(“You must take this course again.”); would be outside the body of the else part of the if and would execute regardless of whether the grade is less than 60. The switch Selection Structure The switch selection structure is an efficient decision-making structure that simplifies choosing among several actions. It avoids complex nested if/else structure. The switch structure is called a multiple-selection structure because it selects among many different actions (or groups of actions). The syntax of the switch statement is: switch (expression)
where label itemizes the values of the expression for which the action should be taken. The expression can be any numeric or string expression. Each action consists of one or more statements. The default case is optional. If the default statement is not present, program execution continues with the statement following the switch control block. The keyword switch is used to identify the beginning of the switch selection structure. The entire body of the structure is enclosed with braces ({}). Each condition is identified with the case keyword. If no condition is met, the single keyword default can be used to identify a default action statement. The program will read through each case statement, and if a condition is met, the action statement will be executed. The program continues through the rest of the case statements to evaluate other conditions. This process repeats until the end of the case statement is reached, or until a break statement, indicated by the keyword break, occurs. A break statement is used to exit control structures such as the switch structure. The break statement is an example of a jump control, because it allows you to jump out of the script block being executed. The general switch structure with a break statement in each case is flowcharted in Figure 15-25.
The flowchart makes it clear that each break statement at the end of a case causes control to exit from the switch structure immediately. The break statement is not required for the last case in the switch structure (or the default case, when it appears last), because program control automatically continues with the next statement after the switch structure. Figure 15-26 shows the script of a switch selection structure example. This example demonstrates different HTML list formats determined by the value input by the user. Figure 15-27 shows the sample result of the program.
Note that this example demonstrates a nested control structure. One switch structure is nested in the if part of the if/else structure, and another switch is nested in the else part. The flow of control with the if/else structure tests variable choiceType to determine which list type to be demonstrated. Then the flow of control with the switch structure demonstrates one of different list styles determined by the value of variable choiceStyle input by the user. The statement
choiceType = window.prompt("Select a list type:\n" + have two separate lines of text in the HTML document. Remember that statements in JavaScript are separated with semicolons (;). Therefore, this two-line text represents one statement. JavaScript allows large statements to be split over many lines. However, you cannot split a statement in the middle of a string.
Also note that the two characters “\” and “n” are not displayed in the prompt dialog box. The backslash (\) in a string is an escape character. It indicates that a “special” character is to be used in the string. When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. The escape sequence \n is the newline character. In a dialog box, the newline character causes the cursor (the current screen position indicator) to move to the beginning of the next line in the dialog box. Figure 15-28 lists some other common escape sequences. You can also use the escape character in combination with other characters to insert a special character into a string. For example document.write(“My city\’s zip code is 01234.”); displays the string My city’s zip code is 01234. Also notice that since the escape character itself is a backslash, you must use the escape sequence “\\” to include a backslash as a character in a string. For example, to include the path “C:\Web\files\” in a string, you must include two backslashes for every single backslash you want to appear in the string, as in the following statement: document.write(“The file is located in C:\\Web\\files\\”); 15.6 Repetition Control Structure In the program studied so far, the statements in the program body execute only once. Sometimes, you want a program to execute the same action statements more than once. For example, you might want to list all the grades in your student grading-book. You could list each grade individually, and if the grading-book had 50 students, you would create 50 statements to write out each grade. However, using a repetition structure, you can repeat action statements or control statements any number of times. To list all 50 grades would require approximately several lines of code, using a repetition structure. If the number of students in your class increases, the number of lines of code will remain the same.
Programmers use the repetition structure, also called looping, to tell the computer to repeat one or more program statements either a specific number of times or until some condition, referred to as the loop condition, is met. The statements contained in the loop are called the body of the loop, and may consist of a single statement or several statements. Each repetition of a loop is called an iteration. A variable that keeps track of the number of iterations is referred to as a loop index variable or simply count. An update statement is used to determine how to change the loop index variable. If you do not include an update statement, the program will continue to run until the browser program is exited, or the computer is turned off. When the loop continues without a natural ending, it is called an infinite loop. It is important to prevent your code from going into an infinite loop.
The loop uses a conditional expression to determine when to stop—the loop stops when the conditional expression is true. The conditional expression often tests to see whether the loop index variable equals a number, or another variable. Usually, the conditional expression tests to see whether a variable is equal to a predetermined number. As the program runs, the update statement within the script block alters the loop index number. If the conditional expression never return false, then the loop becomes an infinite loop. You can reverse this situation by modifying the conditional expression and using different comparison operators.
JavaScript provides four types of repetition structures, namely while, do/while, for and for/in. This chapter describes while, do/while, and for structures. These looping structures vary in their syntax and looping methods. However, all of them allow you to repeat blocks of code within your script.
The while and do/while Repetition Structure
The while repetition structure will repeat a block of code for as long as a conditional expression is evaluated true. The syntax for while structure is while (conditional expression) {
action statements; update statement; } The conditional expression is identified by the keyword while. Variables used within the conditional expression should be declared before the keyword while is used. The update statement will alter one of the variables within the conditional expression. After the iteration is completed, the conditional expression is evaluated again. If the conditional expression is evaluated as true, the script continues processing the while loop. Eventually, the condition will become false. At this point, the repetition terminates, and the first statement after the repetition structure is executed.
As an example of a while structure,
consider a program segment designed to find the first power of 2 larger than
1000. Suppose variable
When the while
structure is entered, product is 2. Variable
The do/while repletion structure is similar to the while structure. In the while structure, the loop-continuation condition is tested at the beginning of the loop before the body of the loop is performed. The do/while structure tests the loop-continuation condition after the loop body is performed. Therefore, the loop body is always executed at least once in do/while structure. When a do/while terminates, execution continues with the statement after the while clause. The syntax for do/while structure is do {
action statements; update statement; } while (conditional expression);
Thus, the preceding while structure example can be written in do/while structure. Figure 15-32 illustrates the flowchart and script code of the preceding example, using do/while structure. The flowchart makes it clear that the loop-continuation condition is not executed until the action is performed at least once. Note that it is not necessary to use braces in the do/while structure if there is only one statement in the body. However, the braces are usually included to avoid confusion.
The for Repetition Structure
The for structure, also called an automatic counter loop, repeats a block of statements a specified number of times. The syntax of the for loop is
for (initialization; conditional expression; increment) action statements;
where the
Figure 15-33 shows the flowchart of an example, and Figure 15-34 gives the script code of the example. We can see that the for loop performs three tasks:
Therefore, we can see that the for repetition structure essentially requires four elements:
The increment expression in the for structure acts like a stand-alone statement, thus, the expressions
++ counter counter++ counter = counter + 1 counter += 1
are all equivalent in the incrementing portion of the for structure. The increment expression of a for structure may be negative, in which case it is really a decrement and the loop actually counts downward. For example, the following example varies the control variable counter from 20 to 2 in steps of –2:
The for structure performs essentially the same function as the while statement. Sometimes, using a for structure instead of while structure simplifies the program somewhat, since you do not need as many lines of code. For instance, the following while structure: var counter = 1; while (counter <=5) {
document.write(counter); ++counter; }
can be created more efficiently using a for structure as follows: for (var counter = 1; counter <= 5; ++counter) {
document.write(counter); }
There are times, however, when using a while structure is preferable to using a for structure. If you do not use a counter to update the conditional expression or if the counter must be updated from the body of the loop statement, a while structure works better than a for structure. The following code relies on a Boolean value returned from a confirm dialog box, rather than a counter, for program control. var i = true while (i == true) i = window.confirm(“Do you want to redisplay this dialog box?”);
If you use a for
structure instead of a while structure in the above example, you must
leave the increment expression out of the for statement. You must also
remember to leave in the semicolon that separates the conditional expression
from the increment expression. If you leave the increment expression in the
for statement, you could create an infinite loop. The following code
performs essentially the same task as the above while example, but causes
an infinite loop, since the for statement always changes the
for (var i = true; i == true; i = true) {
i = window.confirm(“Do you want to redisplay this dialog box?”); }
To make the above for loop function correctly without causing an infinite loop, you must remove the increment expression from the statement, as follows: for (var i = true; i == true;) {
i = window.confirm(“Do you want to redisplay this dialog box?”); }
The break and continue Statements
The break and continue statements alter the flow of control. The break statement, when executed in a while, for, do/while or switch structure, cause immediate exit from that structure. Execution continues with the first statement after the structure. Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch structure. The break statement can be used in other repetition structure. Consider the following problem: A man invests $1,000 in a saving account yielding 5.5% interest. He wants to withdraw the investment when his money doubles, assuming that all interest is left on deposit. He also wants to print the amount of money in the account at the end of each year. This problem involves a loop that performs the indicated calculation for each of the years the money remains on deposit. However, we don’t know how many years it would take to double the investment. Figure 15-35 demonstrates how we can use the break statement in a for repetition structure to solve this problem. Figure 15-36 shows the result of the program.
The for structure
in the example executes its body 100 times, varying control variable
JavaScript does not
include an exponentiation operator. Instead, we use the Math object’s
pow method for this purpose.
performs this calculation from the formula
In the statement document.write(“<TD>” + Math.round(amount * 100)/100 + “</TD>”);
the expression
The continue statement, when executed in a while, for or do/while structure, skips the remaining statements in the body of that structure and proceeds with the next iteration of the loop. In while and do/while structures, the loop-continuation test is evaluated immediately after the continue statement is executed. In the for structure, the increment expression is executed, then the loop-continuation test is evaluated.
Figure 15-37 uses
continue in a while structure that puts parentheses around negative
numbers when it prints the output. When the continue statement executes,
the remainder of the while structure’s body is skipped. Program control
continues with the loop-continuation test to determine whether the loop should
continue executing followed by the increment of the control variable
The break statement can break out of an immediately enclosing while, for, do/while or switch structure. The continue statement proceeds with the next iteration of the immediately enclosing while, for or do/while structure. You can use labeled statements to break out of nested loops or to continue a loop outside the current one. You create a label statement by using the following syntax:
where
A labeled statement provides an identifier that can be used as the destination of a break or continue statement. You can think of it as setting a bookmark in your script. Labeled statements are commonly used in nested looping structures. If you find a labeled statement, you should expect a break or continue statement in the code nearby. Because it’s standard programming practice to use labeled statements in conjunction with break or continue statements, be judicious in their use. To help others interpret your code, we recommend that you restrict your use of labels to their recommended purpose.
The script in Figure 15-39 starts by showing a simple continue statement, then adds labeled statements so you can see how the script executes under different conditions. Figure 15-40 shows the result.
Random Number Generation In scientific research, engineering, and business applications, we often use random numbers. Consider a specific collection of numbers. We say that a process selects a number at random from this collection if any number in the collection is just as likely to be selected as any other and the number cannot be predicted in advance. Figure 115-41 shows some examples of random number.
In JavaScript, the Math object's random method, which acts like the spinner in Figure 15-41, returns a random number. Consider the following statement: var randomValue = Math.random(); randomly assigns a floating-point number from 0 up to (but not including) 1 by the method Math.random(). A different number will be assigned each time Math.random() is called in the program, and any number greater than or equal 0 and less than 1 is just likely to be generated as any other. In other words, if Math.random() truly produces values at random, every value from 0.0 up to (but not including) 1.0 has an equal probability (chance) to being chosen each time Math.random() is called. The range of values produced directly by Math.random() is often different from what is needed in a specific application. For example, a program that simulates coin tossing might require only 0 for "heads" and 1 for "tails". A program that simulates rolling a six-sided die would require random integers in the range 1 to 6. A program that randomly selects the next type of spaceship (out of four possibilities) that will fly across the horizon in a video game might require random integers in the range 0 through 3. With appropriate scaling, the Math.random() method can generate random numbers from other collection. The statement var randomValue = Math.floor(a + Math.random() * b):
If you want to know more about JavaScript, please click the following links: Appendix A: JavaScript: Functions
|