In Lesson 3, you began using JavaScript to store values and display messages in Web pages. While all of the examples so far have been text based, JavaScript allows for computation involving numbers and boolean (true/false) values as well. In this lesson, you will study the basic data types of JavaScript and the operations defined for those types.
So far, you have used the JavaScript write statement to display messages. Such messages, text enclosed in quotes, are known as strings. In addition to strings, data values in JavaScript can also be numbers and booleans (true/false values that will be explored in Lesson 8). Each of the data types in JavaScript has operators predefined for manipulating values of that type. For example, you have already seen that strings can be concatenated using '+'. Not surprisingly, the standard arithmetic operators '+' (addition), '-' (subtraction), '*' (multiplication), '/' (division), and '%' (remainder) are also predefined for numbers.
JavaScript variables can be assigned values of any type, including numbers and numeric expressions. For example, the first assignment below stores the value 24 in the memory cell corresponding to variable x. The second assignment stores the value 1024 in y's memory cell, leaving x unchanged.
var x;
x = 24;x
24 var y;
y = (100 * 10) + 24;x
24 y
1024
Similarly, JavaScript write statements can be used to display values of any type, including numbers and numeric expressions. For example,
EXERCISE 4.1: Trace the execution of the following JavaScript code. For declarations and assignments, draw each memory cell along with its contents. For write statements, list the output that would be displayed.var value1; value1 = 14; var value2; value2 = 8 - (3 + 2); document.write(" value1 = " + value1 + ", value2 = " + value2); var x; x = 99 / 2; var y; y = 99 % 2; var z; z = 99 % 3; document.write("
x = " + x + ", y = " + y + ", z = " + z); x = 2 * 3 * 4 * 5; document.write("
x = " + x);
Verify your predictions by cut-and-pasting the above code into a Web page and loading that page in the browser. You do not need to save or print this page, but do make sure you understand why your predictions are or are not correct.
EXERCISE 4.2: The following formula can be used to convert a temperature in degrees Fahrenheit to Celsius.tempInCelsius = (5/9) * (tempInFahr - 32); Create a Web page named ftoc.html that prompts the user for a temperature in degrees Fahrenheit and stores it in the
tempInFahrvariable. Your code should compute the corresponding temperature in Celsius using this formula and display it in the page. For example, if the user enters 32 at the prompt, the page might display:You entered 32 degrees Fahrenheit. That's equivalent to 0 degrees Celsius. Include your complete HTML page as your answer for this exercise. Be sure that you declare all of the variables that you use. In addition, use your page to convert each of the following temperatures from Fahrenheit to Celsius, and report the corresponding temperatures.
98.6 Fahrenheit 100 Fahrenheit 212 Fahrenheit 0 Fahrenheit
EXERCISE 4.3: Create a Web page named ctof.html that performs the opposite conversion, from degrees Celsius to Fahrenheit, using the inverted formula:tempInFahr = (9/5) * tempInCelsius + 32; Include your complete HTML page as your answer for this exercise. In addition, use your page to convert each of the following temperatures from Celsius to Fahrenheit, and report the corresponding temperatures.
0 Celsius 20 Celsius -10 Celsius 88 Celsius
Numbers in JavaScript have several interesting characteristics. In order to improve readability, JavaScript automatically displays very large or very small values using scientific notation. For example, if you attempted to display the number 2000000000000000000000000 using a JavaScript write statement, it would be displayed as 2e24, symbolizing 2 times 10 to the 24th power. In general, the scientific notation XeY represents the value (X * 10Y).
Not surprisingly, the range of numbers that can be represented inside a computer is limited. For example, 1e308 (which represents a one followed by 308 zeros!) is representable in JavaScript, but 1e309 is not. If you try to evaluate 1e309, it will be treated as "Infinity". Similarly, 1e-323 is representable, but 1e-324 is treated as 0.
Even within this range of numbers, it should be obvious that not all number values are representable. Between any two numbers, there lie infinitely more numbers, so representing all values within any range is impossible. Instead, JavaScript is able to represent only so many significant digits. For example, the number 0.9999999999999995 (with fifteen 9's to the right of the decimal) is handled exactly, but 0.99999999999999995 (with sixteen 9's) is rounded up to the value 1.
EXERCISE 4.4: Display the value of the expression (1e100 + 0.01) in a Web page. What does this expression evaluate to in JavaScript? Can you explain why? You do not need to save or print this page, but you do need to include your explanation in your solutions.
In general, the right-hand side of an assignment statement can be any expression. When an assignment statement is executed, the expression on the right-hand side is evaluated first, and then the resulting value is assigned to the variable on the left-hand side. For example, in the first assignment below, the right-hand side is a simple number value, 14, which is assigned to the variable x. In the second assignment, the right-hand side is a more complex expression that evaluates to 331, which is then assigned to y. In the last assignment, the right-hand side is an expression involving the variables x and y. Since x has the value 14 and y has the value 331 when this assignment occurs, the sum evaluates to 345, which is then assigned to z.
var x;
x = 14;x
14 var y;
y = 33 * 10 + 1;x
14 y
331 var z;
z = x + y;x
14 y
331 z
345
EXERCISE 4.5: Trace the execution of the following JavaScript code, drawing the contents of memory cells after each declaration or assignment and listing the output of each write statement.var a; a = 14; var b; b = 2 * a; document.write(" a = " + a + ", b = " + b); a = b + b; document.write("
a = " + a + ", b = " + b); var x; x = (112 % 5) * 2; message = "
x = " + x; document.write(message); x = 0; document.write(message); document.write("
x = " + x);
Verify your predictions by cut-and-pasting the above code into a Web page and loading that page in the browser. You do not need to save or print this page, but do make sure you understand why your predictions are or are not correct.
In mathematics, where '=' is used for equality, an expression such as the following wouldn't make much sense.
In JavaScript, however, you must keep reminding yourself that "=" is used for assigning values to variables, not for testing equality. As in any assignment, the expression on the right-hand side of an assignment is evaluated first using the current values of variables. Then, the value of that expression is assigned to the variable on the left-hand side of the assignment. In this example, the result is that the current value of x is incremented by one, and the result is assigned back to x.
To avoid confusion, try to refrain from using the word "equals" when referring to the "=" operator. Instead, say "gets" to emphasize the fact that an assignment statement gives the variable on the left-hand side a value. Thus, "x = x + 1" should be read as "x gets x + 1".
EXERCISE 4.6: Trace the execution of the following JavaScript code, drawing the contents of memory cells after each declaration or assignment and listing the output of each write statement.var q; q = 0; q = q + 3; document.write(" q = " + q); q = q * q; document.write("
q = " + q); var word; word = "foo"; word = word + "-" + word; document.write("
word = " + word);
Verify your predictions by cut-and-pasting the above code into a Web page and loading that page in the browser. You do not need to save or print this page, but do make sure you understand why your predictions are or are not correct.
Sometimes, the order in which an expression is evaluated is important to the final result. For example, consider the expression, (2 + 4 * 5). If the addition is performed first, the expression will evaluate to 30. If the multiplication is done first, however, the expression will evaluate to 22.
In any programming language, precedence rules define the order of evaluation for such expressions. In JavaScript, multiplication has precedence over addition, so the multiplication will be performed first (resulting in 22). Addition and subtraction have the same precedence, as do multiplication and division. If more than one operator of the same precedence appears in an expression, they are evaluated from left-to-right. Thus,
Of course, you can always force a particular order of evaluation by using parentheses. In fact, it is inadvisable to rely too heavily on the precedence rules and left-to-right nature of evaluation. If you write a complex expression, parenthesize it to make sure that the desired order is used. Parenthesing complex expressions also makes it easier for human readers of your programs to understand them.
EXERCISE 4.7: Try to predict the value of each of the following expressions.3 + 3 * 2 + 1 10 / 2 * 5 7 - 2 - 4 7 - (2 - 4) 3 * (5 / 2) + 2 * 8 Verify your predictions by displaying the value of each of these expressions in a Web page. You do not need to save or print this page, but do make sure you understand why your predictions are or are not correct.
Recall that the '+' operator performs double duty in JavaScript, representing addition when applied to numbers but concatenation when applied to strings. When applied to a string and a number, the '+' operator automatically converts the number value into a string and then concatenates. For example,
If proper care is not taken, mixed expressions involving string and numbers can produce unexpected results. Since expressions are evaluated from left to right, the similar expressions below yield substantially different results:
EXERCISE 4.8: What do each of the following expressions evaluate to? Describe the steps involved in each evaluation for full credit."My favorite number is " + 10 + 24 "My favorite number is " + (10 + 24) "My favorite number is " + 10 + "" + 24 Verify your predictions by displaying the value of each of these expressions in a Web page. You do not need to save or print this page, but do make sure you understand why your predictions are or are not correct.
When reading in numbers using the prompt function, special care must be taken. The prompt function always returns the user's input in the form of a string, even when they enter a number. For example, the input value 500 would be returned by prompt as "500". Usually, this is not a problem since JavaScript will automatically convert the string to a number when a numeric operation (such as '*' or '-') is applied. However, addition is a problem since the '+' operator may be interpreted as string concatenation. Consider the following seqeuence of JavaScript statements.
One more is " + (myNumber + 1));
If the user entered 12 as their number, the write statement would actually display the message "One more is 121, since myNumber is considered to be a string and so concatenation would be used in the expression (myNumber + 1). Fortunately, JavaScript provides a predefined function for explicitly converting strings to numeric values. The parseFloat function takes one input, a string representing a number (such as "500") and returns the corresponding number value. For example, the modified code below would display "One more is 13" when given the input value 12.
One more is " + (myNumber + 1));
EXERCISE 4.9: Trace the execution of the following JavaScript code, drawing the contents of memory cells after each assignment and listing the output of each write statement. Assume that the user enters the value 1024 at the prompt.var x; x = prompt("Enter a number", ""); document.write(" Double " + x + " is " + (2 * x)); document.write("
Double " + x + " is " + (x + x)); x = parseFloat(x); document.write("
Double " + x + " is " + (x + x));
Verify your predictions by cut-and-pasting the above code into a Web page and loading that page in the browser. You do not need to save or print this page, but do make sure you understand why your predictions are or are not correct.
When programming in JavaScript or any other programming language, variables serve a variety of purposes. Your first use of variables was in storing input values. Using the prompt function, you were able to read in a value, store it in a variable, and then display that value using a write statement (see greet.html in Lesson 3).
A second use of variables was in defining easily modifiable values. In your Old MacDonald page in Lesson 3, you stored an animal name and sound in variables, and then referred to those variables when displaying a verse. To modify the code so that it displayed the "pig" verse instead of the "cow" verse, you only had to change the assignments to these variables. Each occurrence of a variable in the verse would then refer to the new value and so the desired verse would be displayed. Changing each value once in the variable assignments is clearly preferable to changing each occurrence of it in the verse itself.
Now that you know how to build more complex expressions using operators, a third use of variables becomes apparent. A variable can be used to store intermediate results in a complex computation, and so break that computation into simpler, more manageable pieces. For example, consider the task of computing roll call grades for this course. One possible scheme would weight averages as follows:
If you were to attempt to construct a single expression that computed your average given the individual scores (six lessons, five labs, and one test score), it would be complex indeed. Such an expression would be difficult to read and would invite typographical errors due to its complexity. As an alternative, variables could be used to store intermediate values. For example, the six lesson scores could be averaged and stored in a variable named lessons. Similarly, the lab scores and test scores could be averaged and stored in a variable named labs. Having done so, the formula for computing the roll call average would simply be:
EXERCISE 4.10: Create a Web page named grades.html that prompts the user for their individual scores for the course and computes their roll call average using the above grading scheme. Your code should use variables to store intermediate values in the computation, and should display the individual scores and averages as well as the roll call average. For example, the page might appear as follows:Your lesson scores were: 92 92 80 100 92 80 Lesson average = 89.33333333333333 Your lab scores were: 80 75 90 85 80 Lab average = 82 Your test 1 score was: 86 Your roll call average is 84.86666666666666 Note: Entering twelve scores via prompts can become quite tedious. In later lessons, you will learn more efficient and intuitive techniques for obtaining input in a Web page.
EXERCISE 4.11: Use your Web page to determine what your roll call average would be given the following grades:lessons: 80 80 92 92 92 100 labs: 80 85 85 90 95 test1: 75