Previous Page TOC Index Next Page Home


3

Working with Data and Information

In order to move beyond outputting text and very basic user interaction, it is necessary to be able 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 using expressions.

To help you master variables and expressions, this chapter covers the following topics:

Data Types in JavaScript

JavaScript 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.

Type


Example


Numbers

Any number, such as 17, 21.5 or 54e7

Strings

"Greetings!" or 'Fun!'

Boolean

Either true or false

Null

A special keyword for exactly that—the null value (that is, nothing)

Literals

The 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.

Numbers

The 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.

Integers

Integers 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 being used to run 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).


Base 8 numbers only can have digits up to 7 so that a decimal value of 18 would be an octal value of 22. Similarly, Hexadecimal allows digits up to F, where A is equivalent to decimal 10 and F is 15. So, a decimal value of 18 would be 12 in hexadecimal notation.

In order to distinguish between these three bases, JavaScript uses the notations outlined in Table 3.2 to specify the different bases.

Number System


Notation


Decimal (base 10)

A normal integer without a leading 0 (zero) (e.g. 752)

Octal (base 8)

An integer with a leading 0 (zero) (e.g. 056)

Hexadecimal (base 16)

An integer with a leading 0x or 0X (e.g. 0x5F or 0XC72)

Floating Point Values

Floating point values can include a fractional component. A floating point literal can include 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:

Floating point literals must, at a minimum, include a decimal integer and either the decimal point or the exponent indicator ("e" or "E"). As with integers, floating point values can be positive or negative.


It should be noted that JavaScript's handling of floating point numbers can introduce inaccuracy into some calculations. You should keep this in mind your programs.

Strings

You 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:

The last example is called the empty string. It is important to note that the empty string is distinct from the null value in JavaScript.

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.


Unlike Java, C, and other languages, in JavaScript boolean values can only be represented with true and false. Values of 1 and 0 are not considered boolean values in JavaScript.

The null Value

The 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.

Casting

JavaScript 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 it's 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.

This process is known as casting. The first example casts the number 10 into a string, and the second casts the string 10 into a number.

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 Variables

In 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 Variables

In 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 to keep track of the scope of variables (discussed in the 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 to it of "An Example". Because JavaScript allows variables to also be declared on first use, the command example = "An Example" would also achieve the same result.


New Term

The equal sign (=) used in assigning a value to a variable is known as an assignment operator. Assignment operators are discussed later in this chapter.

To better understand how to declare, assign, and use variables, the following code segment produces output similar to Figure 3.1.

var example="An Example";

document.write(example);


Figure 3.1. Variables can hold string literals, numbers, or Boolean values.

Valid Variable Names

Like 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 Script

Using variables, it is possible to simplify the personalized "Welcome to Netscape Navigator 2.0!" 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.

<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 2!</H1>");

// STOP HIDING FROM OTHER BROWSERS -->

</SCRIPT>

</BODY>

</HTML>

Analysis

There are several things to note in this script. First, the part of the script that needs to execute before things are displayed is in the header of the script. This helps ensure that nothing else can be loaded and evaluated until after the user provides a name.

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 variable 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.

End of Analysis

<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 2!</H1>");

// STOP HIDING FROM OTHER BROWSERS -->

</SCRIPT>

</BODY>

</HTML>

Output

This script produces a sequence of results similar to Figures 3.2, 3.3 and 3.4.


Figure 3.2. We store the first name in name.


Figure 3.3. The second name can then also be assigned to name.


Figures 3.4. The final value of name is the second name.

End of Output

Analysis

In this example, you see how assigning a new value to a variable completely replaces the previous value. Rather than combining the user's name with the friend's name, the final value of name is just the friend's 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.

Using two variables it would be possible to provide a final greeting to both users.

You will notice that the alert dialog box with the first name seems small. It is important to note that if you use a longer name, the size of the box is adjusted to accommodate the longer name.

End of Analysis

Working with Variables: Expressions

In 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 their 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, you have several kinds of expressions:

Assignment Expressions

Assignment 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.


NewTerm

Technically, the element to the left of the operator is called the left operand and the element to the right is called the right operand.

Operator


Description


=

Assigns value of right operand to the left operand

+=

Adds the left and right operands and assigns the result to the left operand

-=

Subtracts the right operand from the left operand and assigns the result to the left operand

*=

Multiplies the two operands and assigns the result to the left operand

/=

Divides the left operand by the right operand and assigns the value to the left operand

%=

Divides the left operand by the right operand and assigns the remainder to the left operand


The %= operand assigns the modulus to the left operand. That is x %= y is the same as x = x % y. The modulus is the remainder when two numbers are divided.

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.


There are other assignment operators known as bitwise assignment operators, such as <<=, >>=, and ^=, but these are advanced and require an understanding of binary (base 2) numbers.

Other Operators

Besides 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.


NewTerm

An operator requiring a single operand is referred to as a unary operator and one that requires two operands is a binary operator.

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 which adds 15 and 3, then adds the result (18) to the value of x, and assigns the final result to x.

Arithmetic Operators

The 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 of 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 it's 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 Operators

Logical operators include both binary and unary operators. They take boolean values as operands and return boolean values, as outlined in Table 3.4.

Operator


Description


&&

Logical "and"—returns true when both operands are true; otherwise it returns false.

||

Logical "or"—returns true if either operand is true. It only returns false when both operands are false.

!

Logical "not"—returns true if the operand is false and false if the operand is true. This is a unary operator and precedes the operand.

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:

For example, if x equals 10 and y equals 20, then the expression (x > y) && (x < y) would immediately evaluate to false once the first part of the expression (x > y) is evaluated to false. Likewise, (y > x) || (x > y) is evaluated to true simply because the first part of the expression (y > x) is true. These examples use comparison operators, which are discussed in the next section.

Because the logical "not" operator (!) takes a single operator, there is no short-circuit evaluation for it.

Comparison Operators

Comparison 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 a number of other conditions. Table 3.5 lists the comparison operators available in JavaScript.

Operator


Description


==

Returns true if the operands are equal

!=

Returns true if the operands are not equal

>

Returns true if the left operand is greater than the right operand

<

Returns true if the left operand is less than the right operand

>=

Returns true if the left operand is greater than or equal to the right operand

<=

Returns true if the left operand is less than or equal to the right operand

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.

3 < 1 returns false.

5 >= 4 returns true.

"the" != "he" returns true.

4 == "4" returns true.


When comparing string and numeric values, it is important to realize that if the string value begins with non-numeric characters, JavaScript will generate an error.

Conditional Operators

Conditional 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 either evaluates to 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 Operators

In Chapter 2, you learned to use the concatenation operator (+). Concatenation returns the union of two strings so that

"Welcome to " + "Netscape Navigator 2.0!"

evaluates to a single string with the value "Welcome to Netscape Navigator 2.0!" 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 2.0!";

would assign the string "Welcome to Netscape Navigator 2.0!" to the variable welcome.

Operator Precedence

Because expressions can be the operands for other expressions, it is necessary to understand operator precedence. Operator precedence is the set of rules which determine the order in which these compound expressions are evaluated.

The operators you have learned are evaluated in the following order (from lowest precedence to highest):

Assignment operators (= += -= *= /= %=)

Conditional (?:)

Logical or (||)

Logical and (&&)

Equality (== !=)

Relational (< <= > >=)

Addition/subtraction (+ -)

Multiply/divide/modulus (* / %)

Parentheses (())

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 over-ridden 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 Response

In this example, you go beyond the "Welcome to Netscape Navigator 2.0!" 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.

<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>

</HTML>

Output

The results of this script would look like Figures 3.5 and 3.6.


Figure 3.5. The prompt dialog box is used to test the user.


Figure 3.6. Conditional operators determine the final Web page.

End of Output

Analysis

In this example, you can see the use of several of the concepts learned earlier in this chapter and in earlier sections.

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—all take place in the header. The script in the body of the HTML document only outputs 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.

End of Analysis

Applying Comparison: if-else Constructs

Now 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 another when the condition is false.

Still, 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, it is possible to 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,

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.

Using, this technique it would be possible to 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 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.

It is important to 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 Repetition

Using the if statement, you are going to extend Listing 3.3 one step—you are going to allow the user to indicate if he 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.

<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>

</HTML>

Analysis

In order to add the second chance, you have only to add two embedded if statements. In order to grasp how this works, let's look at the program line by line starting with the first prompt() method.

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 if 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 will be stored in the response variable, replacing the previous answer.

End of Analysis

Summary

JavaScript 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 either numeric, string, or boolean type and 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

Command/Extension


Type


Description


var

JavaScript command

Declares a variable

=

Assignment operator

Assigns the value of the right operand to the left operand

+=

Assignment operator

Adds together the operands and assigns the result to the left operand

-=

Assignment operator

Subtracts the right from left operand and assigns the result to the left operand

*=

Assignment operator

Multiplies together the operands and assigns the result to the left operand

/=

Assignment operator

Divides the left by the right operand and assigns the result to the left operand

%=

Assignment operator

Divides the left by the right operand and assigns the remainder to the left operand

+

Arithmetic operator

Adds together the operands

-

Arithmetic operator

Subtracts the right from the left operand

*

Arithmetic operator

Multiplies together the operands

/

Arithmetic operator

Divides the left by the right operand

%

Arithmetic operator

Divides the left by the right operand and calculates the remainder

&&

Logical operator

Evaluates to true when both operands are true

||

Logical operator

Evaluates to true when either operand is true

!

Logical operator

Evaluates to true if the operand is false and to false if the operand is true

==

Comparison operator

Evaluates to true if the operands are equal

!=

Comparison operator

Evaluates to true if the operands are not equal

>

Comparison operator

Evaluates to true if the left operand is greater than the right operand

<

Comparison operator

Evaluates to true if the left operand is less than the right operand

>=

Comparison operator

Evaluates to true if the left operand is greater than or equal to the right operand

<=

Comparison operator

Evaluates to true if the left operand is less than or equal to the right operand

+

String operator

Combines the operands into a single string

if

JavaScript command

Executes a command or command block if a condition is true

else

JavaScript command

Executes a command or command block if the condition of an associated if statement is false

parseInt()

JavaScript function

Converts a string to an integer number

parseFloat()

JavaScript function

Converts a string to a floating point number

confirm()

JavaScript method

Displays a message in a dialog box with OK and Cancel buttons.

Exercises

  1. Evaluate each of the following expressions:

    a. 7 + 5

    b. "7" + "5"

    c. 7 == 7

    d. 7 >= 5

    e. 7 <= 7

    f. (7 < 5) ? 7 : 5

    g. (7 >= 5) && (5 > 5)

    h. (7 >= 5) || (5 > 5)

  2. Write the segment of a script that would ask the user if he wants a greeting message and, if he does, display a GIF file called welcome.gif and display "Welcome to Netscape Navigator 2.0!" in the document window following the GIF.

  3. Extend Listing 3.4 so that if users answer correctly, they have the choice to answer a second question, but they only get one chance to answer the second question.

Answers

  1. The expressions evaluate as follows:

    a. 12

    b. "75"

    c. true

    d. true

    e. true

    f. 5

    g. false

    h. true

  2. The following code uses the confirm() method and an if statement to complete the task:

    if (confirm("Click OK to see a welcome message")) {
    document.write('<IMG SRC="welcome.gif">');
    document.write("<BR><H1>Welcome to Netscape Navigator 2.0!</H1>");
    }

  3. In order to add this functionality, use an if-else construct:

    <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>

Previous Page TOC Index Next Page Home