5.2.1 Arithmetic OperatorsArithmetic operators take numerical values (either literals or variables ) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction ( “), multiplication (*), and division (/). See Table 5.2. Table 5.2. Arithmetic operators.
Example 5.3<html> <head><title>Arithmetic Operators</title></head> <body> <h2>Arithmetic operators</h2> <p> 1 <script language="JavaScript"> 2 var num1 = 5; var num2 = 7; 3 var result = num1 + num2; 4 document.write("<h3>num1 + num2 = "+ result ); 5 result = result + (10 / 2 + 5); 6 document.write("<h3>12 + (10 / 2 + 5) = " + result ); 7 </script> </body> </html> EXPLANATION
5.2.2 Shortcut Assignment OperatorsThe shortcut assignment operators allow you to perform an arithmetic or string operation by combining an assignment operator with an arithmetic or string operator. For example, x = x + 1 can be written x+=1 . See Table 5.3. Table 5.3. Assignment operators.
Example 5.4<html> <head> <title>Assignment and Shortcut Operators</title> 1 <script language = "JavaScript"> 2 var num=10; 3 document.write("<font size='+1'>" + "<br>" + "num is assigned " + 10); 4 num += 2; document.write("<br>num += 2; num is " + num ); 5 num = 1; document.write("<br>num = 1; num is " + num); 6 num *= 3; document.write("<br>num *= 3; num is " + num); 7 num %= 5; document.write("<br>num %= 5; num is " + num); 8 </script> </head> <body bgcolor="yellow" text="blue"> EXPLANATION
5.2.3 Autoincrement and Autodecrement OperatorsTo make programs easier to read, to simplify typing, and, at the machine level, to produce more efficient code, the autoincrement (++) and autodecrement ( “ “) operators are provided. The autoincrement operator performs the simple task of incrementing the value of its operand by 1, and the autodecrement operator decrements the value of its operand by 1. The operator has two forms: the first form prefixes the variable with either ++ or “ “ (e.g., ++x or “ “ x) ; the second form postfixes (places the operator after) the variable name with either ++ or “ “ (e.g., x++ or x “ “). For simple operations, such as x++ or x “ “, ++x or “ “x, the effect is the same; both ++x and x++ add one to the value of x, and both “ “ x and x “ “ subtract one from the value of x . Now you have four ways to add 1 to the value of a variable:
and four ways to subtract 1 from the value of a variable:
Refer to Table 5.4. In "Loops" on page 101, you'll see these operators are commonly used to increment or decrement loop counters. Table 5.4. Autoincrement and autodecrement operators.
Autoincrement and Autodecrement Operators and AssignmentThe placement of the operators does make a difference in more complex expressions, especially when part of an assignment; for example, y = x++ is not the same as y = ++x .
Example 5.5<html> <head><title>Autoincrement and Autodecrement</title></head> <body> <script language = "JavaScript"> 1 var x=5; var y=0; 2 y = ++x; // add one to x first; then assign to y document.write("<h3>Preincrement:<br>"); 3 document.write("y is " + y + "<br>"); document.write("x is " + x + "<br>"); document.write("<br>"); 4 var x=5; var y=0; 5 y=x++; // assign value in x to y; then add one to x document.write("<h3>Postincrement:<br>"); 6 document.write("y is " + y + "<br>"); document.write("x is " + x + "<br></h3>"); </script> </body> </html> EXPLANATION
5.2.4 Concatenation OperatorAs shown in previous examples, the + sign is used for concatenation and addition. The concatenation operator, the + sign, is a string operator used to join together one or more strings. In fact, the concatenation operator is the only operator JavaScript provides to manipulate strings. In the example, "correct" + "tion" + "al" , the result is "correctional" . If the operands are a mix of strings and numbers , JavaScript will convert the numbers to strings . For example, "22" + 8 results in "228" , not 30 . If the operands are numbers, then the + sign is the addtion operator as in 5 + 4 . But suppose we say, "22" * 1 + 4 . In this case, JavaScript sees the multiplication operator (*) and converts the string "22" to a number, resulting in 22 + 4 or 26 . Netscape Navigator provides the JavaScript console for testing these expressions or you can type javascript: in the URL, followed by the expression you want to test, as shown in Figures 5.6 and 5.7. Figure 5.6. Evaluating expressions in the javascript: URL. The result of the test, 26 , is displayed in the browser window.
Figure 5.7. Concatenation of a string and a number.
The concatenation operator is summarized in Table 5.5. To explicitly convert strings to numbers, JavaScript provides builtin functions called parseInt() and parseFloat() , discussed in Sections 5.3.1 and 5.3.2, respectively. Table 5.5. The concatenation operator.
5.2.5 Comparison OperatorsWhen operands are compared, relational and equality operators are used. The operands can be numbers or strings. The result of the comparison is either true or false ”a Boolean value. Strings are compared letter by letter (lexographically) using Unicode ^{ [1] } values to represent the numeric value of each letter; thus, "A" is less than "B" , and when comparing "Daniel" with "Dan", "Daniel" is greater than "Dan" . When comparing strings, JavaScript pads "Dan" with three spaces to make it the same length as " Daniel" . Refer to Table 5.6.
Table 5.6. Comparison operators.
What Is Equal?In an ideal world, there would be equality between the sexes and among the races and religions, but in the real world equality is a debatable topic, often determined by governments . In JavaScript, operators determine the equality or inequality of their operands, based on more specific rules. When using the == or != equality operators, the operands may be of any given data type ”numbers, strings, Booleans, objects, arrays, or a combination of these ”and there are rules that govern whether they are equal. For example, two strings are equal when they have the same sequence of characters, same length, and same characters in corresponding positions . Two numbers are equal when they have the same numeric value. If a string is compared with a number, they are equal if the number has the same characters as the string; for example, "500" is equal to 500. NaN (Not a Number) is not equal to anything, including NaN . Positive and negative zeros are equal. Two objects are equal if they refer to the same object. Two Boolean operands are equal if they are both true or both false. Null and undefined types are equal. To test any of the expressions shown in Table 5.7, use the JavaScript Console. Figure 5.8 shows an example using Netscape. Figure 5.8. Testing the equality of two strings. Is "William" equal to "william" ? Nope.
Table 5.7. Equality test with strings and numbers.
What Is Identical?Men are equal; clones are identical. The === and !== equality operators test that its operands are not only of the same value, but also of the same data type. String "54" is equal to number 54 , but not identical because one is a string and the other is a number, even though their values are equal. See Table 5.8. Table 5.8. Identity test with strings and numbers.
Comparing NumbersWhen the comparison operators are used to compare numbers, numeric values are compared; as in, is 50 > 45 ? A Boolean value of either true or false is returned.
Example 5.6<html> <head> <title>Comparing Numbers</title> </head><body> 1 <script language = "JavaScript"> 2 var x = 5; var y = 4; 3 var result = x > y; 4 document.writeln("<h3>The result is "+ result + ".<br>"); 5 result = x < y; 6 document.writeln( "The result is " + result + ".<br>"); 7 </script> </body> </html> EXPLANATION
Comparing StringsThe difference between comparing strings and numbers is that numbers are compared numerically and strings are compared alphabetically , based on the ASCII character set. The strings are compared letter by letter, from left to right, and if they are exactly the same all the way to end, they are equal. Once a letter in one string differs from the corresponding letter in the second string, the comparison stops and each of the differing letters is evaluated. For example, if the string "Dan" is compared with "dan" , the comparison stops at the first letters D and d. "Dan" is smaller than "dan" , because the letter D has a lower ASCII value than the letter d. D has an ASCII decimal value of 68, and d has an ASCII value of 100. To avoid the casesensitivity issue when comparing strings, JavaScript provides the builtin string functions, toUpperCase() and toLowerCase(), discussed in "Free Form and Reserved Words" on page 17 and Table 9.10 on page 184.
Example 5.7<html> <head> <title>Comparing Strings</title> </head><body> 1 <script language = "JavaScript"> 2 var fruit1 = "pear"; var fruit2 = "peaR"; 3 var result = fruit1 > fruit2; 4 document.writeln( "<h3>The result is "+ result + ".<br>"); 5 result = fruit1 < fruit2; 6 document.writeln( "The result is " + result + ".<br>"); 7 result = fruit1 === fruit2; // Are they identical; i.e., value and type are the same? 8 document.writeln( "The result is " + result + ".<br>"); </script> </body> </html> EXPLANATION
5.2.6 Logical OperatorsThe logical operators allow you combine the relational operators into more powerful expressions for testing conditions and are most often used in if statements. They evaluate their operands from left to right, testing the Boolean value of each operand in turn : Does the operand evaluate to true or false? In the expression if ( x > 5 && x < 10 ), the && is a logical operator. The expression simplified means, "if x is greater than 5 and x is also less than 10, then do something"; in the case of the logical AND ( && ), if the first expression returns true and the second expression also returns true , then the whole expression is true. If instead of && we used , the operator means OR and only one of the expressions must be true. Sometimes the result of a test is not Boolean. When logical operators have numeric operands, such as 5 && 6 , the result of the entire expression is the value of the last evaluated expression. A numeric operand is true if it evaluates to any number that is not zero. 5, “2, and 74 are all true. is false. For example, when using the && (AND) operator, both operands must be true for the whole expression to be true. The value returned from an expression such as 5 && 6 is 6 , the last value evaluated by the operator. 5 is not zero (true) and 6 is not zero (true), therefore, the expression is true. 5 && 0, 0 && 0 and 0 && 5 all yield , which is false. See Table 5.9. The three logical operators are the logical AND, logical OR, and logical NOT. The symbol for AND is && , the symbol for OR is , and the symbol for NOT is ! . Table 5.9. Logical operators and their functions.
The && Operator (Logical AND)We all know the meaning of the English statement, "If you have the money and I have the time...." Whatever is supposed to happen is based on two conditions, and both conditions must be met. You must have the money and I must have the time. JavaScript uses the symbol && to represent the word AND. This operator is called the logical AND operator. If the expression on the lefthand side of the && evaluates to zero, null, or the empty string "", the expression is false. If the expression on the lefthand side of the operator evaluates to true ( nonzero ), then the righthand side is evaluated, and if that expression is also true, then the whole expression is true. If the lefthand side evaluates to true, and the righthand side is false, the expression is false. If evaluated as Booleans, the same rules apply, except the returned value will be either Boolean true or false . See Table 5.10. Table 5.10. Logical AND examples.
Example 5.8 <html> <head><title>Logical AND Operator</title> </head> <body bgcolor="lightblue"> <font="+1"> <script language="JavaScript"> 1 var answer = prompt("How old are you? ", ""); 2 if ( answer > 12 && answer < 20 ) { alert("Teenagers rock!"); } </script> </body> </html> EXPLANATION
The Operator (Logical OR)In the English statement "If you have some cash or I have a credit card..." the word or is used in the condition. With the or, only one of the conditions must be met (hopefully that you have the cash!). JavaScript uses the symbol to represent the logical OR. If the expression on the lefthand side of the operator is evaluated as true (nonzero), the value of the expression is true, and no further checking is done. If the value on the lefthand side of the operator is false, the value of the expression on the righthand side of the operator is evaluated, and if true, the expression is true; that is, only one expression must be true. Once an expression returns true, the remaining expressions can be either true or false. It doesn't matter, as long as one expression is true . Refer to Table 5.11. Table 5.11. Logical OR examples.
Example 5.9<html> <head> <title>Logical OR Operator</title> </head> <body bgcolor="lightblue"> <font="+1"> <script language="JavaScript"> 1 var answer = prompt("Where should we eat? ", ""); 2 if ( answer == "McDonald's" answer == "Taco Bell" answer == "Wendy's"){ 3 alert("No fast food today, thanks."); } </script> </body> </html> EXPLANATION
The ! Operator (Logical NOT)In the English statement "That's not true!" the word not is used for negation: not true is false, and not false is true. JavaScript provides the NOT ( ! ) operator for negation. The ! operator is called a unary operator because it has only one operand; for example, ! true or ! 5 . It returns true if the expression evaluates to false and returns false if the expression evaluates to true. See Table 5.12. Table 5.12. Logical NOT examples.
Example 5.10 <html> <head> <title>Logical NOT Operator</title> </head> <body bgcolor="lightblue"> <font="+1"> <script language="JavaScript"> 1 var answer = true; 2 alert("Was true. Now " + ! true ); </script> </body> </html> EXPLANATION
In summary, the following example illustrates the logical operators and the values they return. Example 5.11<html> <head> <title>Logical (Boolean) Operators</title> </head> <body> <script language = "JavaScript"> 1 var num1=50; var num2=100; var num3=0; 2 document.write("<h3>num1 && num2 is " + ( num1 && num2 ) + ".<br>"); 3 document.write("num1 $num2 is " + ( num1 num2 ) +".<br>"); 4 document.write("! num1 is " + !num1 +".<br>"); 5 document.write("!(num1 && num2) is " + !(num1 && num2) + ".<br>"); 6 document.write("!(num1 && num3) is " + !(num1 && num3) + ".<br>"); </script> </body> </html> EXPLANATION
5.2.7 The Conditional OperatorThe conditional operator is called a ternary operator because it requires three operands. It is often used as a shorthand method for if/else conditional statements. (See Chapter 6, "Under Certain Conditions.") Although we cover if/else in Chapter 6, the format below shows both the conditional operator and how it translates to an if/else statement. FORMAT conditional expression ? expression : expression Examples: x ? y : z If x evaluates to true, the value of the expression becomes y, else the value of the expression becomes z big = (x > y) ? x : y If x is greater than y, x is assigned to variable big , else y is assigned to variable big The same conditional operator as an if/else statement: if (x > y) { big = x; } else{ big = y; } Example 5.12 <html> <head> <title>Conditional Operator</title> </head> <body bgcolor="lightblue"> <font="+1"> <script language="JavaScript"> 1 var age = prompt("How old are you? ", ""); 2 var price = (age > 55 ) ? 0 : 7.50; 3 alert("You pay $" + price + 0); </script> </body> </html> EXPLANATION
5.2.8 Bitwise OperatorsBitwise operators treat their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numeric values. Refer to Table 5.13. Table 5.13. Bitwise operators.
When using the bitwise operations &, , ^ , and “ , each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. For example, the binary representation for 5 & 4 is 101 & 100. 101 101 101 & 100 100 ^ 100    100 101 001 Bitwise Shift OperatorsThe bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.
Shift operators convert their operands to 32bit integers and return a result of the same type as the left operator. Example 5.13<html> <head> <title>Bitwise Operators</title> </head> <body bgcolor="lightblue"> <font size="+1" face="arial"> <h3> Testing Bitwise Operators</h3> <script language="JavaScript"> 1 var result = 15 & 9; document.write("15 & 9 yields: " + result); 2 result = 15 9; document.write("<br> 15 9 yields: " + result); 3 result = 15 ^ 9; document.write("<br> 15 ^ 9 yields: " + result); 4 result = 9 << 2; document.write("<br> 9 << 2 yields: " + result); 5 result = 9 >> 2; document.write( "<br> 9 >> 2 yields: " + result); 6 result = 9 >> 2; document.write( "<br> 9 >> 2 yields: " + result); 7 result = 15 >>> 2; document.write( "<br> 15 >>> 2 yields: " + result); </script> </body> </html> EXPLANATION
Figure 5.19. Output from Example 5.13.
