• Create BookmarkCreate Bookmark
• Create Note or TagCreate Note or Tag
• PrintPrint

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>
<script language="JavaScript">
var posNum=85;
var negNum= -posNum;
document.write(negNum);
</script>
<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>
<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>
<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>
<script language="JavaScript">
var bolts=150, lot= 60;
bolts %= lot;
document.write("Odd lot=" + bolts);
</script>
<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.

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>
<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 + " = " + BooleNum;
var part2="<p>Boolean value <b>" + Boole + "</b> plus the string " + string + " = " + BooleString;
var part3="<p>String value <b>" + string + "</b> plus the number " + numnum + " = " + StringNum;
document.write(part1+part2+part3);
</script>
<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.

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>
<title>Minus sign and negative values</title>
<script language="JavaScript">
var posVal=44;
var negVal= -posVal;
var diffVal = (posVal-negVal);
document.write(diffVal);
</script>
<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>
<title>Multiply Numbers in Strings</title>
<script language="JavaScript">
var stringNum="5";
var stringNum2="20";
var mulEm= stringNum * stringNum2;
document.write(mulEm);
</script>
<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>
<title>Divide by Zero Errors</title>
<script language="JavaScript">
var leftOperand=77;
var rightOperand= 20 > 30;
var divEm= leftOperand / rightOperand;
if(!isFinite(divEm)) {
alert("Whoa Dude that\'s a big number!")
}
alert("You are dividing nothing by nothing.")
}
</script>
<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

 Code View: Scroll / Show All``` Modulo two decimal place converter
```

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

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

 Code View: Scroll / Show All``` String comparisons ```

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.

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.

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>
<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>
<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>
<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>
<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>
<title>Bitwise shift</title>
<script language="JavaScript">
var alpha = 3 << 1;
document.write(alpha);
</script>
<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>
<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>
<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>
<title>Delete Element Value</title>
<script language="JavaScript">
delete family[2];
document.write(family[3] + "<p>"+family.length);
</script>
<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.

• Create BookmarkCreate Bookmark
• Create Note or TagCreate Note or Tag
• PrintPrint