Chapter 4. Using Operators and Expressions

CONTENTS

CONTENTS>>

  •  General and Bitwise Operators
  •  General Operators in JavaScript
  •  Operators
  •  Precedence
  •  Summary

The previous Chapters Made Extensive Use of both operators and expressions. This chapter examines the operators and the expressions that they create. In programming, the name "expression" is a bit misleading because both literals and a combination of literals and variable names can be expressions. Thus, this excerpt:

total

is an expression in a line of JavaScript code, as is this:

total + tax + 4.99

So, while an expression is usually envisioned as a combination of literals or variables (complex expressions), expressions can be single variables or literals.

General and Bitwise Operators

To begin an examination of operators and expressions, two very different types of operators are discussed separately. I will refer to nonbitwise operators as "general operators" or simply "operators," while bitwise operators are prefaced by "bitwise." In this next section, Table 4.1 shows an overview of what I call general operators; near the end of the chapter, you will find a separate subsection and Table 4.2 on bitwise operators.

Bitwise operators shift the binary numbers (0s and 1s) in the registers in your computer. When binary numbers are shifted, special types of mathematical operations occur that you normally associate with addition, subtraction, multiplication, and division. To learn more about how this works, consult a good book on binary math. Generally, though, designers do not need to use binary operators or binary math, so if you skip over the section on binary operators, you probably will not miss anything crucial to creating dynamic pages with JavaScript.

General Operators in JavaScript

The everyday garden-variety operators seen in a typical JavaScript program are very similar or identical to the operators found in programs such as C++ or Java. If you have a Basic or Visual Basic programming background, you will find many similarities as well between JavaScript operators and what they use in different types of Basic. However, while a quick glance at the operators shows where the operators are similar and where they differ from your previous programming experience, be sure to take that glance. For readers who are taking up JavaScript as their first language, spend some time going over the examples and descriptions of what the operators do (see Table 4.1).

Table 4.1. JavaScript Operators

Symbol

Operation

+

Add or concatenate

-

Subtract, or negative

*

Multiply

/

Divide

%

Modulus (remainder)

++

Increment

 

Symbol

Operation

-

Decrement

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

&&

Logical AND

||

Logical OR

!

Logical NOT

= =

Test for equality

= = =

Test for strict equality

! =

Test for inequality

! = =

Test for strict inequality

=

Assignment

+ =

Add and assign

- =

Subtract and assign

* =

Multiply and assign

% =

Modulus and assign

/=

Divide and assign

( )

Function arguments

.

Structure member (called a dot) in structure or property

,

Multiple evaluation

[ ]

Array elements (access, index)

,

Multiple evaluation

? :

Ternary operator

new

Constructor

delete

Remove a variable

typeof

Data type

void

Return undefined value

Operators

Operators can be placed into three categories binary, unary, and ternary. Binary operators, most commonly associated with the concept of operator, take two (binary) expressions and combine them into a third complex or compound expression. However, a single expression can have several binary operators. For example, the following variable declaration uses multiple binary operators to define the variable:

var calcAdd = (total / n ) + 73 

The divide (/) operator and the plus (+) operator are binary operators. The first combination occurs when the variable total is divided by the variable n. The two variables become a single value. That single value resulting from total divided by n is then added to the literal numeric value of 73, creating yet another value. The equals sign (=) places the combined value of the operands into the variable calcAdd.

Unary operators work on a single variable or literal. All negative numbers are assigned using a unary operator. For example, the following little script uses a unary operator to create a variable with a negative value:

<html>  <head>  <script language="JavaScript">  var posNum=85;  var negNum= -posNum;  document.write(negNum);  </script>  </head>  <body bgcolor="honeydew">  </body>  </html>

The return of the script is -85 because the minus (-) unary operator defined the variable negNum as the negation of the variable posNum. Other common unary operators include increment or decrement operators (++ and - -) seen in counter variables.

Finally, ternary operators combine three expressions into one. Most commonly used to create a shorthand expression for conditional statements, the only ternary operator in JavaScript is ? :. For example, this conditional statement:

if(alpha == beta) {       gamma=56;        } else {       gamma=57;        } 

can be written with a ternary operator as follows:

alpha == beta ? gamma=56 : gamma=57; 

The following little script shows how both methods arrive at the same conclusion:

<html>  <head>  <script language="JavaScript">  var alpha=20, beta=30, gamma=0, lambda=0;  if (alpha==beta) { var gamma=56;  } else { gamma=57;  }  //Same set of conditions using ternary operator  alpha==beta ? lambda=56 : lambda=57;  document.write("Conditional results:" + gamma + "<p>" + "Ternary conditional:" + lambda);  </script>  </head>  <body bgcolor="oldlace">  </body>  </html>

The three elements that the ?: operator brought together in the example are (alpha==beta), (lambda=56), and (lambda=57). Note also how the comma (,) operator is used in the script to separate the definitions of the variables alpha, beta, gamma, and lambda at the beginning of the script.

Assignment Operators

The key assignment operator is the equals sign (=). The left operand is a variable, an array element, or an object property, and the right operand is either a literal or another variable, array element, or object property. As seen in Chapter 3, "Dealing with Data and Variables," assigning a variable a value can be accomplished with any number of different combinations of variables, array elements, object properties, and literals.

The following provides an idea of the range of assignments:

alpha= 77;  alpha= (fishSize.length / 2);  alpha= (beta > gamma); 

Compound Operators

Operators that include assignment along with an operation are compound operators. These operators work as a shorthand for an assignment plus another operation. For example:

var bankAccount += interest; 

is equivalent to writing

var bankAccount = bankAccount + interest; 

Besides addition, compound operators in JavaScript include subtract assign (-=), multiply assign (*=), divide assign (/=), and modulo assign (%=). For example, the following script uses the modulo compound assignment operator:

<html>  <head>  <script language="JavaScript">  var bolts=150, lot= 60;  bolts %= lot;  document.write("Odd lot=" + bolts);  </script>  </head>  <body bgcolor="lightslategray">  </body>  </html>

The example shows how two operations can be combined into a single one. The variable bolts is divided by the value of the variable lot, and the remainder (modulo) is assigned to the variable bolts. It would be the same as writing this:

var bolts = bolts % lot; 

However, instead of taking two operations, one does the trick of assignment and operation.

Comparison Operators

Probably the area of most mistakes in JavaScript with operators is confusing (or just forgetting) the difference between assignment operators and comparison operators. Assignment operators equate a value with a variable, array element, or object property. Comparison operators generate a Boolean value. For example, the following script returns a false Boolean value:

<html>  <script language="JavaScript">  var wrong= (6==7)  document.write(wrong);  </script>  <body bgcolor="lightslategray">  </body>  </html>

The comparison operator is the double equals sign (= =), and the assignment operator is the equals (=) sign. The most common problem is in a standard conditional statement where the developer types this:

if (alpha = beta) { .... WRONG

when he meant to type this:

if (alpha==beta) { .... RIGHT

In the debugging process, one of the first things to look for is the placement of an assignment operator where an equality operator should be.

The other comparison operators include not equal to (!=) less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (>=). Like the equality operator, these other comparison operators have two roles. One role is part of a conditional statement, and the other is to serve as Boolean literals in definitions as the previous example showed. The following script shows how variables can be defined so that they can contain Boolean literals and then used as part of a conditional statement without the use of comparison operators:

<html>  <script language="JavaScript">  var alpha=25;  var beta=35;  var zeta=(alpha <= beta);  if(zeta) {      var sigma ="This is true."       } else {      var sigma = "This is not true.";       }  document.write(sigma);  </script>  <body bgcolor="lightslategray">  </body>  </html>

In the script, the variable alpha is compared to be less than or equal to (<=) beta in the definition of zeta. Because alpha is less than beta, the variable zeta contains a Boolean value of true. In the conditional statement, no comparative operators are used because the variable beta is already a Boolean value. Because the value is true, it meets the condition to load the variable sigma with the message "This is true."

Strict Equality Operators

JavaScript 1.3 introduced strict equality and inequality operators. These operators test for both equality of value and equality of type. In other words, if both values were 23 but one variable is a string and the other is a number, you might think that they would be unequal anyway. Consider the following script:

<html>  <script language="JavaScript">  var currentWord="75";  var currentNumber=75;  var outcome=(currentWord==currentNumber);  document.write(outcome);  </script>  <body bgcolor="lightsalmon">  </body>  </html>

You might be surprised to find that the variable outcome is true ! The reason for that is that JavaScript tries very hard to resolve numeric and string differences. Remember, if you define a variable as follows, the outcome is a string even though the line mixes numeric and string literals:

var mix = "$" + 12.33; 

The same is true when JavaScript compares two variables where one is a number and one is a string. If the "values" are deemed to be the same even though one is a string and the other is a number, JavaScript helpfully makes them equal, as was seen in the previous script. However, if you had an application where both the values and the type of data are important to compare, you could not make that comparison with standard comparison operators. To fix that problem, JavaScript 1.3 introduced strict equality (===) and inequality (! ==) operators. These operators look at not only the values, but also at the type of variable. In the previous script, change this line:

var outcome= (currentWord==currentNumber); 

to

var outcome= (currentWord===currentNumber); 

Then save the script and run the program again. In the second version of the script, the outcome changes to false. While the numbers are the same, the data types are different. To get a true outcome, change the line to the following:

var outcome= (currentWord! ==currentNumber); 

Both Netscape Navigator 4.7 and Internet Explorer 5 and later recognize strict equality and inequality operators. (Version 4 of Netscape Navigator requires language=JavaScript1.2 in the <SCRIPT> tag, but in later versions of the browser, all you need is language=JavaScript.)

Arithmetic Operators

The basic arithmetic operators in JavaScript are fairly self-explanatory, with a few exceptions. To avoid the few aggravations from these exceptions, each operator is discussed with a focus on uses.

Add and Concatenate (+)

One arithmetic operator that has two different uses is add (+). First, the add operator adds values in math operations. Second, it concatenates (joins) strings or strings and other literals. Mathematical addition is fairly straightforward, but concatenation is not. When the add operation joins a string and a number, it concatenates them and converts the number into a string. For example, the following script joins strings with nonstring literals:

<html>  <head>  <title>Add and Concatenate</title>  <script language="JavaScript">  var Boole= 22 < 90;  var string="250";  var numnum=88;  var BooleNum =Boole + numnum;  var BooleString=Boole + string;  var StringNum=string + numnum;  var part1="Boolean value <b>" + Boole + "</b> plus the number " + numnum + " = " +  graphics/ccc.gifBooleNum;  var part2="<p>Boolean value <b>" + Boole + "</b> plus the string " + string + " = " +  graphics/ccc.gifBooleString;  var part3="<p>String value <b>" + string + "</b> plus the number " + numnum + " = " +  graphics/ccc.gifStringNum;  document.write(part1+part2+part3);  </script>  </head>  <body bgcolor="paleturquoise">  </body>  </html>

The output seen in Figure 4.1 tells the story of what happens when different types of literals are mixed. Whenever a number or a Boolean value is added to a string, it is turned into a string and is concatenated with the string. However, when a Boolean value is added to a number, the value of the Boolean (0 or 1) is added to the number, and the Boolean value is treated as a number instead of true or false. However, when a Boolean and string are combined, the Boolean value is shown as a string true or false.

Figure 4.1. Depending on the use of the add (+) operator, different results can be expected.

graphics/04fig01.gif

Subtract and Negation (-)

The minus sign (-) has two very different uses. First, in arithmetic operations, the subtract operator subtracts the second operand from the first. Hence, this line places the value 7 in the variable alpha:

var alpha = 10-3; 

Second, used as a unary operator, the minus sign changes a positive value to a negative value. Moreover, if a negative value is subtracted from a positive value, the result is the same as adding two positive values. The following script illustrates using both the unary negation and subtraction with the minus (-) sign as an operator. For example, try out the following script and see if you can determine ahead of time what the outcome will be:

<html>  <head>  <title>Minus sign and negative values</title>  <script language="JavaScript">  var posVal=44;  var negVal= -posVal;  var diffVal = (posVal-negVal);  document.write(diffVal);  </script>  </head>  <body bgcolor="papayawhip">  </body>  </html>

If you guessed that the output on the screen would be 88, you are right. The positive value in the variable posVal is 44. The variable negVal is created by the unary negation of posVal. When negVal is subtracted from posVal, the effect is to add the two values. (Just as in grammar, a double-negative creates a positive.)

Multiply (*)

The multiplication operator is simple it multiplies two numbers. However, if you attempt to multiply two strings containing numeric characters, JavaScript attempts to change the strings into numbers and complete the multiplication. For example, try the following script:

<html>  <head>  <title>Multiply Numbers in Strings</title>  <script language="JavaScript">  var stringNum="5";  var stringNum2="20";  var mulEm= stringNum * stringNum2;  document.write(mulEm);  </script>  </head>  <body bgcolor="peru">  </body>  </html>

The output to the screen will be 100. So, the multiply operator (*) can actually convert certain strings into numbers as well as multiply numbers.

Divide (/)

Like the multiply operator, the divide operator (/) works with numbers. In operation, the left operand is divided by the right operand. Also, like the multiply operator, the divide operator attempts to convert a string into a number. The area where division differs most from the other operations is in a divide by zero error. Two different types of returns result. A divide by zero of a number other than 0 results in Infinity, while zero divided by zero returns NaN. The following script demonstrates what returns from both types of divide by zero errors. Also, the script shows how to use the built-in functions isFinite() and isNaN() to test for Infinity and NaN values. In the case of Infinity, the isFinite() function must be negated using the ! operator.

For a designer, the importance of knowing when a divide by zero instance occurs is so that you can keep it from crashing your program. A home-decorating site, for example, has a module that calculates the amount of paint required to paint rooms. A gallon of paint covers 350 square feet. So, somewhere in the calculator, the designer must have a formula that divides 350 by the square feet of the room being painted. Suppose that the viewer forgot to enter a value for the square feet of the room and the script attempted to divide 350 by 0. Rather than sending the viewer into confusion by telling her that she had to purchase an infinite number of gallons of paint, you can trap to divide by zero errors and send any message that you want, as the following script illustrates:

<html>  <head>  <title>Divide by Zero Errors</title>  <script language="JavaScript">  var leftOperand=77;  var rightOperand= 20 > 30;  var divEm= leftOperand / rightOperand;  var nada= 0/0;  document.write(divEm + "<p>" + nada);  if(!isFinite(divEm)) { alert("Whoa Dude that\'s a big number!")  }  if(isNaN(nada)) { alert("You are dividing nothing by nothing.")  }  </script>  </head>  <body bgcolor="springgreen">  </body>  </html>
Modulo (%)

The modulo (%) operator returns the remainder in a division operation. The left operand is divided by the right operand, and only the remainder is returned. While the modulo operator does not come to mind in most applications, it can prove to be an extremely useful operator. For example, the following script uses the operator to convert long decimal places into two-place decimals.

modulo2dec.html
<html>  <head>  <title>Modulo two decimal place converter</title>  <style>  body { background-color: plum;  font-family: verdana;  font-weight: bold;  }  </style>  <script language="JavaScript">  var dec=.06;  var part=77.4;  part += (dec * part);  var wholeInt=Math.floor(part);  //The Math.floor() function rounds the variable 'part' down to the nearest whole integer.  //Prior to obtaining the modulo (remainder) 'part' times 100 is rounded down to the  graphics/ccc.gifnearest whole to obtain an integer remainder.  var fraction=Math.round(part *100)%100;  if (fraction<10) { fraction = "0" + fraction;  }  var fullVal=wholeInt +"." + fraction;  var headTitle="<h2>Modulo Helper</h2>"  var before="Before conversion = " + part + "<p>";  var after="After conversion = " + fullVal;  document.write(headTitle + before + after);  </script>  </head>  <body>  <center>  </body>  </html>

Figure 4.2 shows what the original number looks like before and after the conversion script helped along using modulo.

Figure 4.2. You can use the modulo operator to help write a script to round numbers to two decimal places.

graphics/04fig02.gif

Increment (++) and Decrement (- -) Operators

These operators either add 1 or subtract 1 from an operand. In examples where loops have been used, the counter variable typically increments or decrements using these two operators. This general form in a loop statement is the most common usage of the increment or decrement operator:

for (counter=0; counter<20; counter++) {.... 

The operand connected with these two operators can be preaffected or postaffected. If the operator is in front of the operand, the value is added or subtracted before the next operation. If the operator is at the end of the operand, the addition or subtraction comes after the operation. For example, the following script can be used to show how each affects the operand:

<html>  <head>  <title>Increment/Decrement operator</title>  <script language="JavaScript">  var combine="";  var bounce=0;  for (var counter=0;counter <=5; counter++) {       var Hep=bounce++;        combine += "Hep value =" + Hep + "<br>";        }  document.write(combine);  </script>  </head>  <body bgcolor="palevioletred">  <center>  </body>  </html>

When you run the script, the outcome on the screen is as follows:

Hep value =0  Hep value =1  Hep value =2  Hep value =3  Hep value =4  Hep value =5

The first time through the loop, the variable bounce, originally declared with a value of zero (0), remained zero because the increment in its value is after the definition of the variable Hep. Now change the position of the increment operator to the front of the variable, changing the line to this:

var Hep= ++bounce; 

Now the output shows this:

Hep value =1  Hep value =2  Hep value =3  Hep value =4  Hep value =5  Hep value =6

As can be seen, the position of the increment operator made a fundamental change in the output. With the increment operator in front of the operand, the Hep variable was incremented in the first iteration, but it wasn't until the second iteration that the Hep variable changed when the operator was at the end of the operand. A small change in the code led to a big change in the output. With increment and decrement operators, you must be especially vigilant not to crash a program because the position of the operator is positioned incorrectly.

Operators in the Context of Using String Variables and Literals

As you saw when using the plus (+) operator, numbers can be added or strings and numbers can be concatenated into a single string. So, the idea of a "string operator" is very much a context-dependent concept.

Besides using the plus (+) operator, you can use the comparison operators (>, >=, <, <=, ==, !=) with strings. In using comparison operators, the operator compares the string operands in an alphabetical order based on Unicode character encoding. The higher in the alphabet the character is, the greater the character is in comparison with another character. However, uppercase letters are less than lowercase letters. Therefore, Xray is less than emergency, as far as JavaScript is concerned. The following script shows some relationships between order and uppercase and lowercase strings.

stringOps.html
<html>  <head>  <title>String comparisons</title>  <script language="JavaScript">  var alpha="apples";  var beta="oranges";  var gamma="Apples";  var delta="Oranges";  var lclc=beta > alpha;  var lcuc=alpha > gamma;  var uclc=gamma > alpha;  var banner="<h3>String comparisons</h3>"  var first=beta + " greater than "+ alpha + " results in " + lclc + "<p>";  var second=alpha + " greater than "+ gamma + " results in " + lcuc + "<p>";  var third=delta + " greater than "+ alpha + " results in " + uclc;  document.write(banner+first+second+third);  </script>  </head>  <body bgcolor="mistyrose">  </body>  </html>

Figure 4.3 shows the outcomes that you can expect when working with upperand lowercase comparisons in JavaScript.

Figure 4.3. Strings beginning with lowercase letters are considered greater than those beginning with uppercase letters.

graphics/04fig03.gif

When comparing strings with numbers, a different outcome occurs than when using the plus (+) operator. Instead of turning numbers into strings, JavaScript attempts to turn strings into numbers when making comparisons that involve numeric characters in strings. For example, if you write the following, the variable alpha would be true:

var alpha="10" > 3; 

However, a string with a number followed by character letters does not ignore the letters and make a valid numeric comparison with a numeric operand.

TIP

Whenever you're not sure about what is greater than or less than some combination of numbers, numbers and strings, or strings and strings, use your browser address window as a test bench. Just enter the word javascript:, followed by the operands and operators. Figure 4.4 shows a simple example.

Figure 4.4. You can use the URL window of your browser to test the outcome of different combinations of numbers or strings using comparison operators.

graphics/04fig04.gif

Boolean Operators

The comparison operators result in Boolean outcomes, but three logical operators in JavaScript can be considered Boolean as well. The operators combine different conditions or the negation of a condition.

Logical AND (&&)

A common requirement in a script is for two different conditions to exist for an outcome to be true or false. JavaScript provides the logical AND (&&) operator to determine whether two or more conditions are met. For example, an array search might seek to find all instances of customers who are interested in purchasing a new printer and who live in the state of Iowa so that they can be contacted for a printer trade show in Des Moines. Only if both conditions are true will the outcome be true and added to a contact list. For example, the following script segment searches for two conditions in an array:

for (var seek=0;customers.length;seek++)  if((interest[seek]=="printer") && (state[seek] =="Iowa")) {....

Note that a double set of parentheses have to enclose the script within the if statement. You may also use the logical AND in defining variables. For example, in the following script, the first variable evaluates to true and the second evaluates to false:

<html>  <head>  <title>String comparisons</title>  <script language="JavaScript">  var alpha = (15 < 20) && ("pen" > "Sword");  var beta = ("big" > "tall") && (20 < 30);  document.write(alpha + "<br>" + beta)  </script>  </head>  <body bgcolor="lightcoral">  </body>  </html>
Logical OR (||)

The logical OR operator (||) uses the double pipes as a symbol. When two or more conditions are stated using the logical OR operator, only one of the conditions need be met for the outcome to evaluate as true. For example, the variable alpha in the following would evaluate to true, even though two of the conditions are false:

var alpha = (56 < 34) || (10 > 2) || ("Fred" > "Alice"); 

You may also use the logical OR (or the logical AND) with variables defined with Boolean values. For example, the following lines show how you might use the logical OR in a script:

var alpha = ("beans" > "Potatoes");  var beta = 30 > 40;  var gamma = alpha || beta; 

Because the variable alpha contains a true Boolean value and beta contains a false one, the variable gamma is true because either one or the other has to be true, not both.

Logical NOT (!)

JavaScript's logical NOT (!) serves to negate an outcome. Sometimes, as used elsewhere in this chapter, a built-in function has the opposite of what you might want to test in your script. The isFinite( ) function used in an example elsewhere in this chapter was negated to test for Infinity. The following script shows some different applications of the logical NOT:

<html>  <head>  <title>Logical NOT</title>  <script language="JavaScript">  var alpha = 200/0;  var beta = !isFinite(alpha);  var gamma = !(!alpha);  var delta = !beta;  var b="<br>";  combine = "alpha="+alpha+b+"beta="+beta+b+"gamma="+gamma+b+"delta="+delta;  document.write(combine);  </script>  </head>  <body bgcolor="mintcream">  </body>  </html>

The script generates the following output:

alpha=Infinity  beta=true  gamma=true  delta=false

Because the alpha value generates Infinity, beta should generate true because the function !isFinite() tests for Infinity. However, the gamma variable also generates true. The negation of a variable containing a true Boolean literal generates false, but so will the negation of any other variable with a non-Boolean value. For example, these lines would return false:

var alpha=5, beta=!alpha;  document.write(beta); 

Because alpha does not contain a Boolean value, you might assume that alpha would be "neutral" neither true or false. However, in the script where gamma returns true, a double NOT preceded it !(!alpha). That is because !alpha would generate a Boolean false.

Bitwise Operators

If your script calls for bitwise operations, you can use the symbols in Table 4.2 to guide you. Generally, few programmers require bitwise operators, and they are only included here for a complete list of operators available in JavaScript and for programmers who may need them.

NOTE

Bitwise operations involve binary numbers, and you should understand how and when to effectively use binary numbers in a program. However, you can go through life as a very effective programmer, not to mention designer, and never have cause to use bitwise operators. However, if using bitwise operators is crucial to an envisioned JavaScript program that you have in mind, you will find that JavaScript provides an ample set of bitwise operators.

Table 4.2. Bitwise Operators

Symbol

Operation

&

Bitwise AND

|

Bitwise OR

^

Bitwise XOR

~

Bitwise NOT

<<

Left-shift

>>

Right-shift

>>>

Zero extension in right-shift

In certain respects, bitwise operators are like any others in the sense that you use them in the same kinds of expressions as any other operators in JavaScript. The key difference is that they work with binary (0s and 1s) instead of decimal values. To see what JavaScript is doing with bitwise operators, consider the first seven values in a binary number system:

0000 -0  0001 -1  0010 -2  0011 -3  0100 -4  0101 -5  0110 -6

If the digits in one were shifted to the left by one, the value 1 (0001) would become the value 2 (0010) because the digit in the fourth position from the right is moved to the third position and a 0 fills in where the 1 originally was. Hence, 0001 becomes 0010, or the decimal value 2. Using bitwise operators in JavaScript, you can complete the same kinds of operations. The following shows a single shift to the left, with decimal 3 becoming decimal 6:

<html>  <head>  <title>Bitwise shift</title>  <script language="JavaScript">  var alpha = 3 << 1;  document.write(alpha);  </script>  </head>  <body bgcolor="palevioletred">  </body>  </html>

The output to the screen is 6, but, for JavaScript, it simply shifts 0011 to 0110. Four bit operations are shown, but JavaScript converts the values to 32-bit integers internally so that all floating-point numbers are converted to integers and are rounded down (for example, 3.9999 becomes 3).

Using typeof

The typeof operator is unary, returning one of the following values:

  • number

  • string

  • boolean

  • object

  • function

  • undefined

  • null

To use the operator, type the operator (typeof), a space and the operand, or place the operand in parentheses after the typeof operator. The following script shows the return of an array (object) and a Boolean value (boolean) using both methods of applying the operator:

<html>  <head>  <title>typeof Operator</title>  <script language="JavaScript">  var lots=new Array();  var whatTruth = 10 > 4;  var   kindOfData1= typeof lots;  var kindOfData2 = typeof(whatTruth);  var kindOfData=kindOfData1 + "<p>" + kindOfData2;  document.write(kindOfData);  </script>  </head>  <body bgcolor="wheat">  </body>  </html>

The new, delete, and void Operators

Of these last three operators discussed, new is the most commonly used. All objects must begin with a constructor preceded by the new operator. As seen previously, the array object begins with the new operator:

var family = new Array("Dad","Mom","Sue","Kris"); 

Likewise, other constructors for objects all use new.

The delete operator removes an object property or array element in a script. For example, the following would undefine the array element with the string value Sue:

var family = new Array("Dad","Mom","Sue","Kris");  delete family[2]; 

However, despite the operator's name, the element is not deleted; only the value is. The following script demonstrates what happens:

<html>  <head>  <title>Delete Element Value</title>  <script language="JavaScript">  var family = new Array("Dad","Mom","Sue","Kris");  delete family[2];  document.write(family[3] + "<p>"+family.length);  </script>  </head>  <body bgcolor="peru">  </body>  </html>

The length of the array is still four, and the last element is still Kris. However, the third array element (element[2]), while no longer Sue, still exists. The delete operator simply undefined it.

The final operator, void, is unary and operates on any literal or variable. Usually, you will see this operator as part of an <A> tag in an HTML script, such as here:

<a href="javascript:void(0) "onClick="scroll(500,0)"> 

The void operator suppresses the display of values from evaluated expressions. All the viewer sees is javascript:void(0) in the window in the lower-left corner when the mouse moves over the link instead of the full expression, including the URL.

Precedence

The order in which expressions are evaluated based on their operators is known as precedence. Multiplication and division occur before addition and subtraction, so any operands that are to be multiplied or divided occur before ones that are added and subtracted. Precedence can be reordered by placing expressions within parentheses. The innermost parentheses are evaluated first and work outward. So, if you want two numbers added before multiplication, place them in parentheses. The following two script excerpts show the difference results from different precedence order:

var alpha = 3 * 4 + 7 //alpha's value is 19   12 + 7  var beta = 3 * (4 + 7) // beta's value is 33   3 * 11 

When all of the operators have the same precedence, the evaluations occur from left to right. Table 4.3 is a precedence chart, with the lowest ranks being executed before the higher ones.

Table 4.3. Precedence

Rank

Operators

1

. [] ()

2

++ -- - (negation) ~ ! delete new typeof void

3

* / %

4

+ - (subtraction, addition, or concatenation)

5

<< >> >>> (bitwise shifts)

6

< > <= >=

7

= = != = = = != =

8

& (bitwise)

 

Rank

Operators

9

^ (bitwise)

10

| (bitwise)

11

&&

12

||

13

?: (ternary)

14

= All compound assignments (such as +=, /=, and &=)

15

,

Summary

Operators are truly understood and appreciated only with use and practice. Most debugging of JavaScript is a matter of looking to make sure that all of the characters that make up the bulk of operator symbols are the correct ones and that they are placed where they belong. Of course, memorizing which ones do what is important, but so many of them depend of the context of their use that only lots of practice and debugging work leads to optimum use.

In this chapter and previous chapters, operators were used in the context of legal JavaScript statements. The next chapter examines the different statements that have been used, plus others not yet used in examples. As you will see, doing them effectively requires using them in concert with the set of operators from this chapter. All of the actions in the expressions are controlled by the operators and, in the context of a statement, JavaScript performs different actions.

When a designer understands the JavaScript basics, he is in a position to begin thinking about how to use variables, operators, and data to communicate with the viewer. By recording what the user does in variables, the site can respond in ways limited only by the designer's imagination. For example, if the user moves the mouse over one position, that movement can be placed in the variable alpha simply by changing the value of alpha to record the movement. Likewise, if the user moves to another position, the movement can be recorded in a different variable, beta. Later in the book, you will see how all different types of input from the mouse and keyboard can be used in site design to individualize feedback to viewers based on their movement on the page.

CONTENTS


JavaScript Design
JavaScript Design
ISBN: 0735711674
EAN: 2147483647
Year: 2001
Pages: 25

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