|
|||
|
Click Here! |
Chapter 3Working with Data and Information
CONTENTS
In order to move beyond outputting text and very basic user interaction, it is necessary to work with data and information-both when it is generated by the user and by calculations in a script. JavaScript provides four basic data types that can be used to work with numbers and text. Variables offer containers to hold information and work with it in useful and sophisticated ways by using expressions. To help you master variables and expressions, this chapter covers the following topics:
Data Types in JavaScriptJavaScript uses four data types-numbers, strings, boolean values, and a null value-to represent all the information the language can handle. Compared with most languages, this is a small number of data types, but it is sufficient to intelligently handle most data used in everything except the most complex programs.
The four data types in JavaScript are outlined in Table 3.1.
LiteralsThe term literals refers to the way in which each of the four data types are represented. Literals are fixed values which literally provide a value in a program. For example, 11 is a literal number, "hello" is a string literal, and true is a boolean literal. You have already seen literals in use in the previous chapters when you gave arguments to different methods in the form of text strings such as "Welcome to Netscape Navigator 2.0!" and "Enter Your Name:". For each data type, there are different ways of specifying literals. NumbersThe JavaScript number type encompasses what would be several types in languages such as Java. Using the numbers, it is possible to express both integers and floating point values. IntegersIntegers are numbers without any portion following the decimal point; that is, they are whole numbers-no fractions. Integers can be either positive or negative numbers. The maximum integer size is dependent on the platform running the JavaScript application. In JavaScript, you can express integers in three different bases: base 10 (decimal-what you normally use in everyday situations), base 8 (known as octal), and base 16 (hexadecimal).
In order to distinguish between these three bases, JavaScript uses the notations outlined in Table 3.2 to specify the different bases.
Floating Point ValuesFloating point values can include a fractional component. A floating point literal includes a decimal integer plus either a decimal point and a fraction expressed as another decimal number or an exponent indicator and a type suffix, as shown in the following examples:
StringsYou have already encountered string literals in Chapter 2 "Your First Script," where you used them as arguments for several methods. Technically, a string literal contains zero or more characters enclosed, as you know, in single or double quotes:
Boolean
A boolean literal can take two values: either true or
false. This type of literal comes in handy when comparing
data and making decisions, as you will see later in this chapter.
The null ValueThe null value is a special value in JavaScript. The null value represents just that-nothing. If you try to reference a variable that isn't defined and therefore has no value, the value returned is the null value. Likewise, in a prompt dialog box, if the user selects the Cancel button, a null value is returned. This is distinct from a value of zero or an empty string where this is an actual value. The null value is indicated in JavaScript by the term null. NaNIn addition to these values, some functions return a special value called NaN-which means that the value is not a number. parseInt() and parseFloat() on UNIX systems are an example of functions which returns NaN when the argument passed to them cannot be evaluated to a number. Values can be tested to see if they are NaN by using the isNaN() function which returns true or false based on the nature of the argument passed to the function. CastingJavaScript is what is called a loosely typed programming language. In loosely typed languages, the type of a literal or variable (which we discuss in the next section) is not defined when a variable is created and can, at times, change based on the context. By comparison, Java and C are not loosely typed. In its earliest forms, LiveScript and JavaScript allowed programmers to combine two literals of different types, with the result being a literal value of the same type as the first literal in the expression. For instance, combining the string "Count to " with the integer literal 10 results in a string with the value "Count to 10".
By contrast, adding together the numeric literal 3.5
and the string "10" results in the floating
point numeric literal 13.5.
However, as JavaScript and Java have been brought closer together, this has begun to change. In the version of JavaScript currently available, it is no longer possible to cast a string into a number by using a form such as 0 + "1". JavaScript has added the parseInt() and parseFloat() functions, which convert strings into integers or floating point numbers. For instance, parseInt("13") returns the integer 13 and parseFloat("45.2") returns the floating point number 45.2. It is still possible to cast a number into a string as in "Count to " + 10 evaluating to a string with the value "Count to 10". Creating VariablesIn order to make working with data types useful, you need ways to store values for later use. This is where variables come in. In JavaScript you can create variables that can contain any type of data. Variables have names, and after assigning values to a variable, you can refer to the value by name. If you subsequently assign a new value to the variable, you can continue referring to that new value by the name of the variable. Declaring VariablesIn order to use a variable, it is good programming style to declare it. Declaring a variable tells JavaScript that a variable of a given name exists so that the JavaScript interpreter can understand references to that variable name throughout the rest of the script. Although it is possible to declare variables by simply using them, declaring variables helps to ensure that programs are well organized and helps to keep track of the scope of variables (discussed in Chapter 4 "Functions and Objects-The Building Blocks of Programs"). You can declare a variable using the var command: var example; In this line, you have defined a variable named example, which currently has no value. It is also possible to assign value to a variable when you declare it: var example = "An Example";
Here you have declared the variable named example and
assigned a string value of "An Example" to
it. Because JavaScript allows variables to also be declared on
first use, the command example = "An Example"
would also achieve the same result.
To better understand how to declare, assign, and use variables, the following code segment produces output similar to Figure 3.1. Figure 3.1 : Variables can hold string literals, numbers, or boolean values. var example="An Example"; document.write(example); Valid Variable NamesLike property and method names in JavaScript, variable names are case sensitive. In addition, variable names must start with a letter or an underscore (_). After that, the remaining characters can also include numbers. Incorporating Variables in a ScriptUsing variables, you can simplify the personalized "Welcome to Netscape Navigator " script from the previous chapters. In Listing 3.1, you want to ask for the user's name prior to using document.write() and store the value in a variable.
Listing 3.1. Using variables in the welcome program. <HTML> <HEAD> <TITLE>Example 3.1</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!--HIDE FROM OTHER BROWSERS var name=prompt("Enter Your Name:","Name"); // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS document.write('<IMG SRC="welcome.gif">'); document.write("<H1>Greetings, " + name + ". Welcome to Netscape å Navigator</H1>"); // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </BODY>
Second, you have assigned the result returned by the prompt() method to the variable name in the same way you previously assigned a literal value to a variable. This works because the prompt() method is returning a string value, which can be assigned to a variable. This script also demonstrates how using variables can make scripts easier to read because the names of variables can be carefully selected to impart meaning to someone reading the source code of a script. You can now take using variables a step further and look at how you can assign values to them in succession. In Listing 3.2, you ask for two names in a row.
Listing 3.2. Assigning a new value to the variable. <HTML> <HEAD> <TITLE>Example 3.2</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!--HIDE FROM OTHER BROWSERS var name=prompt("Enter Your Name:","Name"); alert("Greetings " + name + "."); name=prompt("Enter Your Friend's Name:","Friend's Name"); // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS document.write('<IMG SRC="welcome.gif">'); document.write("<H1>Greetings, " + name + ". Welcome to Netscape å Navigator</H1>"); // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </BODY>
Figure 3.2 : Store the first name in name. Figure 3.3 : The second name can then also be assigned to name.
Figure 3.4 : The final value of name is the second name.
In addition, assigning subsequent values to variables works much the same way as assigning values when declaring a variable, except that the var command is not used. By using two variables you can provide a final greeting to both users. You will notice that the alert dialog box with the first name seems small. If you use a longer name, the size of the box is adjusted to accommodate the longer name. Working with Variables-ExpressionsIn order to make variables useful, you need to be able to manipulate variables and evaluate them in different contexts. This ability is provided by expressions. At its most basic, an expression is nothing more than a collection of variables, operators, and other expressions-all of which evaluate to a single value. In practical terms, that means there are two types of expressions: those that simply have a value and those that assign a value to a variable. You have seen simple examples of both: example = "An Example" is an expression that assigns a value to the variable, example, while "The Number is " + "10" is an example of an expression that simply has value. As with data types, JavaScript has several kinds of expressions:
Assignment ExpressionsAssignment expressions use assignment operators to assign value to a variable. The typical structure of an assignment expression is: variable operator expression
In other words, the operator assigns a value to the variable by
performing some type of operation on the expression. Table 3.3
outlines the assignment operators in JavaScript.
For example, if x = 10 and y = 5, then x
+= y sets x to 15, x *= y sets
x to 50, x /= y sets x to
2, and x %= y sets x to zero because
the remainder of 10 divided by 5 is zero.
Other OperatorsBesides the assignment operators we have already discussed, JavaScript also has operators for expressions that simply evaluate to a value. These are the arithmetic operators, string operators, and logical operators, as well as the bitwise operators, which are beyond the scope of this book.
As you will see in the following examples, these operators include
both operators that require two operands and those that require
a single operand.
In addition, all the operators under discussion here can take expressions as their operands. In these cases, the expressions that act as operands are evaluated before evaluating the final expression. For example, in the next section, you will learn about simple arithmetic expressions such as 15 + 3. Because operators can take other expressions as their operands, you could write an expression such as x += 15 + 3. This adds 15 and 3, then adds the result (18) to the value of x, and assigns the final result to x. Arithmetic OperatorsThe standard binary arithmetic operators are the same as those on a basic calculator: addition (+), subtraction (-), multiplication (*), and division (/). In addition to these basic operators is the modulus (%) operator, which, as mentioned before, calculates the remainder after dividing its operands. The following are examples of valid expressions using these: 8 + 5 32.5 - 72.3 12 % 5 In addition to these binary operators, there are three unary arithmetic operators that are quite useful: increment (++), decrement (--) and unary negation (-). Both the increment and decrement operators can be used in two different ways: before the operand or after. For example, ++x increments x by one and returns the result, while x++ returns x and then increments the value of x. Similarly, --x decreases the value of x by one before returning a result, while x-- returns the value of x before decreasing its value by one. For example: x = 5; y = ++x; z = x++; In these lines of code, x is first assigned the value of 5, then it is increased to 6 and assigned to y. Then, the new value of 6 is assigned to z and the value of x is increased to 7. So, at the end, x is 7, y is 6, and z is 6. Unary negation works a little differently. The operator must precede its single operand, and the result is the negation of the operand. Typically, the usage of this operand looks like this: x = -x; Here, if the value of x is 5, then it becomes -5. Likewise, if x were -4, it would become 4. Logical OperatorsLogical operators include both binary and unary operators. They take boolean values as operands and return boolean values, as outlined in Table 3.4.
In discussing logical operators and expressions, it is necessary to discuss short-circuit evaluation. With short-circuit evaluation, JavaScript will finish evaluating an expression after evaluating the first (left) operand, if the first operand provides sufficient information to evaluate the expression. Short-circuit evaluation uses the following rules: Because the logical "not" operator (!) takes a single operator, there is no short-circuit evaluation for it. Comparison OperatorsComparison operators are similar to logical operators in that they return boolean values. Unlike logical operators, they don't require that their operands be boolean values. Comparison operators are used to compare the value of the operands for equality as well as for a number of other conditions. Table 3.5 lists the comparison operators available in JavaScript.
In JavaScript, all comparison operators are binary operators. Comparison operators can be used to compare numbers as well as strings; for instance: 1 == 1 returns true.
Conditional OperatorsConditional expressions are a little different than the others you have seen so far because a conditional expression can evaluate to one of two different values based on a condition. The structure of a conditional expression is: (condition) ? val1 : val2 The way a conditional expression works is that the condition, which is any expression that can be evaluated to a boolean value, is evaluated; based on the result, the whole expression evaluates to either val1 (true condition) or val2 (false condition). The expression (day == "Saturday") ? "Weekend!" : "Not Saturday!" evaluates to "Weekend!" when day is "Saturday". Otherwise, the expression evaluates to "Not Saturday!". String OperatorsIn Chapter 2 you learned to use the concatenation operator (+). Concatenation returns the union of two strings so that "Welcome to " + "Netscape Navigator" evaluates to a single string with the value "Welcome to Netscape Navigator." As with numbers, this can be done with a short cut concatenation operator. For example, if the variable welcome has the value "Welcome to ", then welcome += "Netscape Navigator"; would assign the string "Welcome to Netscape Navigator" to the variable welcome. Operator PrecedenceBecause expressions can be the operands for other expressions, it is necessary to understand operator precedence. Operator precedence is the set of rules that determines the order in which these compound expressions are evaluated. The operators that you have learned are evaluated in the following order (from lowest precedence to highest): Assignment operators (= += -= *= /= %=) Based on these rules, the expression 5 + 3 * 2 evaluates to 5 + 6 which evaluates to 11. Without these rules, the addition operator would be evaluated before the multiplication operator and the result would be 16. Likewise, the expression false || true && false evaluates to false because the && expression is evaluated to false first, and then the || expression (which becomes false || false) evaluates to false. The rules of operator precedence can be overridden by the use of parentheses. Expressions in parentheses evaluate before those outside the parentheses, so that the expression (5 + 3) * 2 would evaluate to 16, instead of 11 without the parentheses. Testing a User's ResponseIn this example, you go beyond the "Welcome to Netscape Navigator 2" scripts you have been working on to something a little different. In Listing 3.3, you will pose a test question to the user and based on the answer, display a different result for the user in the form of one of two different GIF images. The question will be presented in a prompt dialog box, and the result displayed by outputting to the client window.
Listing 3.3. Using conditional operators to test input. <HTML> <HEAD> <TITLE>Example 3.3</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS // DEFINE VARIABLES FOR REST OF SCRIPT var question="What is 10+10?"; var answer=20; var correct='<IMG SRC="correct.gif">'; var incorrect='<IMG SRC="incorrect.gif">'; // ASK THE QUESTION var response = prompt(question,"0"); // chECK THE ANSWER var output = (response == answer) ? correct : incorrect; // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS // OUTPUT RESULT document.write(output); // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </BODY>
Figure 3.5 : The prompt dialog box is used to test the user.
Figure 3.6 : Conditional operators determine the final
Web page.
The first part of the script appears in the header because this is the advisable style, except where the script must generate output in sequence with the HTML file. For this reason, all the variable declarations-asking the question and checking the answer-take place in the header. The script in the body of the HTML document outputs only the final results. Notice the extensive use of variables, both strings and numbers, all declared with the var command. Every important item in the script is assigned to a variable. This makes the script easier to read and easier to change. By changing the question and answer variables, you can change the test, and by changing the correct and incorrect variables, you can change the response given to the user. In addition, you see a practical example of conditional expressions ((response == answer) ? correct : incorrect) and how the value of a conditional expression can be assigned to a variable. Applying Comparison: if-else ConstructsNow that you know how to create expressions and, more importantly, how to create comparison expressions and logical expressions, you are ready to apply them. In the preceding section you saw how an expression, such as a comparison, could be the condition in a conditional expression. The conditional operator gives you a simple way to make a decision: evaluate to one value when the condition is true and to another when the condition is false. Still, by using conditional expressions, you cannot break beyond the bounds of a linear program flow. That is, every line of the script is evaluated and executed in order-you still can't alter the order. Using the if-else construct, combined with expressions, you can alter the flow of a program-to determine which sections of program code run based on a condition. At its most simple structure, the if statement is used as follows: if condition command; That is, if the condition is true, execute the command. Otherwise, don't execute it and skip to the next command or condition following. As you learned in Chapter 2 however, commands can be grouped together in command blocks using curly braces. The if statement can be used with command blocks as well: if condition { several lines of JavaScript code } For example, these lines if (day == "Saturday") { document.writeln("It's the weekend!"); alert("It's the weekend!"); } will write "It's the weekend!" to both the document window and an alert dialog box only if the variable day has the value "Saturday". If day has any other value, neither line is executed. By using this you can have a different message for both Saturday and every other day of the week: if (day == "Saturday") { document.writeln("It's the weekend!"); } if (day != "Saturday") { document.writeln("It's not Saturday."); } The if-else construct provides an easier way to do this by using else: if (day == "Saturday") { document.writeln("It's the weekend!"); } else { document.writeln("It's not Saturday."); } The else construct allows the creation of a command block to execute when the condition in the associated if statement is false. Also, note that if-else constructs can be embedded: if condition1 { JavaScript commands if condition2 { JavaScript commands } else { Other commands } More JavaScript commands } else { Other commands } Using if for RepetitionUsing the if statement, you are going to extend Listing 3.3 one step-you are going to enable the user to indicate if she wants a second chance to answer the question correctly, as shown in Listing 3.4. What you want to do is ask the question and check the result. If the result is incorrect, you will ask the user if she wishes to try again. If she does, you ask one more time. In order to make this easier, you will use the confirm() method, which is similar to the alert() and prompt() methods that you already know how to use. The confirm() method takes a single string as an argument. It displays the string in a dialog box with OK and Cancel buttons and returns a value of true if the user selects OK or false if Cancel is selected.
Listing 3.4. The confirm() method with the if statement. <HTML> <HEAD> <TITLE>Example 3.4</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS // DEFINE VARIABLES FOR REST OF SCRIPT var question="What is 10+10?"; var answer=20; var correct='<IMG SRC="correct.gif">'; var incorrect='<IMG SRC="incorrect.gif">'; // ASK THE QUESTION var response = prompt(question,"0"); // chECK THE ANSWER THE FIRST TIME if (response != answer) { // THE ANSWER WAS WRONG: OFFER A SECOND chAncE if (confirm("Wrong! Press OK for a second chance.")) response = prompt(question,"0"); } // chECK THE ANSWER var output = (response == answer) ? correct : incorrect; // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS // OUTPUT RESULT document.write(output); // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </BODY>
var response = prompt(question,"0"); In this line, you declare the variable response, ask the user to answer the question and assign the user's answer to response. if (response != answer) Here, you compare the user's response to the correct answer. If the answer is incorrect, then the next line is executed. If the answer is correct, the program skips down to output the result. if (confirm("Wrong! Press OK for a second chance.")) The user has made an incorrect response. Now you check whether the user wants a second chance with the confirm() method, which returns a boolean value, which is evaluated by the if statement. response = prompt(question,"0"); If the user selects OK in the confirm dialog box, the confirm() method returns true, and this line executes. With this command, the user is again asked the question, and the second response is stored in the response variable, replacing the previous answer. SummaryJavaScript has four basic data types: numeric (both integer and floating point), string, boolean, and the null value. Literals, which literally express a value, can be of numeric, string, or boolean type; specific rules govern the format of these literals. Variables, which are named containers to hold data and information in a program, are declared using the var statement. Because JavaScript is a loosely typed language, the type of literals and variables change dynamically depending on what actions are performed on them or with them. Expressions provide a means to analyze and work with variables and literals. There are several types of expressions, including assignment expressions, arithmetic expressions, logical expressions, comparison expressions, string expressions, and conditional expressions. Expressions are made up of a series of operands and operators that evaluate to a single value. The rules of operator precedence tell you the order in which compound expressions will be evaluated. Parentheses can be used to override operator precedence. The if-else construct enables you to decide which program code will be executed based on the value of variables, literals, or expressions. In Chapter 4 we will look at functions and objects as the building blocks for most programs. Commands and Extensions Review
Exercises
Answers
<HTML> <HEAD> <TITLE>Exercise 3.3</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS // DEFINE VARIABLES FOR REST OF SCRIPT var question="What is 10+10?"; var answer=20; var correct='<IMG SRC="correct.gif">'; var incorrect='<IMG SRC="incorrect.gif">'; // ASK THE QUESTION var response = prompt(question,"0"); // chECK THE ANSWER THE FIRST TIME if (response != answer) { // THE ANSWER WAS WRONG: OFFER A SECOND chAncE if (confirm("Wrong! Press OK for a second chance.")) response = prompt(question,"0"); } else { // THE ANSWER WAS RIGHT: OFFER A SECOND QUESTION if (confirm("Correct! Press OK for a second question.")) { question = "What is 10*10?"; answer = 100; response = prompt (question,"0"); } } // chECK THE ANSWER var output = (response == answer) ? correct : incorrect; // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS // OUTPUT RESULT document.write(output); // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </BODY> </HTML> |
Use of this site is subject certain Terms & Conditions. Copyright (c) 1996-1999 EarthWeb, Inc.. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Please read our privacy policy for details. |