Chapter 7
Operators and Expressions
In This Chapter
If this chapter were a sequel to the previous one-and it is-it would pick up where we left off. And it will. Variables, values, and objects are merely part of the JavaScript story. They all deal with ways to contain data. In this chapter, you're going to look at methods of manipulating data, to generate new and improved--or at least useful--data. I guarantee this will be fun, or else you get a free video rental from your local video store down the street. Tell them I sent you; they'll take care of you.
An operator is a command that interprets given values or variables and produces a result. Does that make any sense? Perhaps not, but that's a textbook definition. As usual, examples are the best explanation.
A common and easy-to-understand form of operators are arithmetic operators. They are used to perform calculations on given data. Here is an arithmetic operator:
+
Neat, huh? That's not nearly so confusing as the definition made it seem. Of course, + can't perform anything on its own--it needs data to work with. Here's where values come in, either in the form of variables or literals. In technotalk, the values used with an operator are called operands. Thus, consider the following:
3 + 8
In the above, 3 and 8 are operands, and the + is the operator. That example used literals for values; more commonly in JavaScript programs, you would see operands that are variables:
total = mugs * price
The asterisk (*) is the operator for "multiply." JavaScript offers a wide array of arithmetic operators, which you can use with your values, be they literals or variables (or variables in the form of properties of objects). The following table attractively highlights some of the common arithmetic operators available in JavaScript.
Common Arithmetic Operators for Fun and Profit
| Operator |
What It Does |
| + |
addition |
| - |
subtraction |
| * |
multiplication |
| / |
division |
| % |
modulus (returns the remainder of a division) |
The preceding arithmetic operators are known as binary operators. This is because they work their magic given two values (binary meaning "two"). That is why the binary syntax, as illustrated in the examples, can generally be described as
operand1 operator operand2
A couple of notable unary operators exist. These only call for one operand, and it will be a variable. There are three unary operators in JavaScript to know: increment, decrement, and negation. Here's an example of each.
This operator will increase, by one, the value of the operand (variable) supplied to it. Thus, mugs++ will increase the value of the current value of mugs by 1. You might (as detailed further later in this chapter) use this in an assignment:
sales = mugs++
Note the position of the ++ relative to mugs. In the preceding example, sales will be assigned the current value of mugs, and then the value of mugs will be increased by 1. This is as opposed to
sales = ++mugs
Here, mugs will first be increased by 1, and that result will be assigned to sales. This is an important distinction, because if you use one but meant the other, your later calculations may be off by 1.
This operator works just as the unary increment, but in the opposite direction. It decreases the value of the specific variable operand by one. Therefore, the operator mugs-- will decrease the value of mugs by 1.
You can use the unary decrement operator in assignments just as you use the unary increment. Again, keep in mind the difference between --mugs and mugs-- when used in an assignment (as explained in the previous unary increment section).
Finally, there is the unary negation operator. Simply, it negates the value of the operand. Thus, if the variable mugs currently holds the value 5, then
-mugs
Would return the value -5. If mugs was already -5, then the unary negation operator would return the value 5 (because the negation of -5 is 5).
There are several other varieties of operators besides arithmetic. Each one works by relating two or more variables together in some way. Operators are of central importance in JavaScript programming, as they are the main way to evaluate current conditions and change future conditions. Let's take a spin through the nonarithmetic operators: assignments, comparisons, and logicals.
You've already encountered one form of assignment operator: the equal sign (=). This is the most basic and common assignment operator and, as discussed, is used to assign one value--either a literal or a variable--to a variable.
price = 9.95
price = cost
In the first case, a literal is assigned to the variable price. In the second case, the current value of the variable cost (whatever that may be) is assigned to the variable price. Simple enough.
The other assignment operators are shortcuts to arithmetic operators, which combine assignments and arithmetic in one fell swoop. Witness:
total += price
In longhand, using the aforementioned arithmetic operators, the above could also be written
total = total + price
One common application of this technique is in updating a running total. Perhaps you're keeping track of cumulative gross profit and want to keep adding any new purchase orders to that gross. If the current value of total was 10, and price was 5, then the above would sum those two values and assign the new result (15) back to the variable total. Note that both of the above methods produce exactly the same result. The += method is simply shorter to write.
Similarly, you can also use the following hybrid assignment operators:
total -= price SAME AS total = total - price
total *= price SAME AS total = total * price
total /= price SAME AS total = total / price
total %= price SAME AS total = total % price (see arithmetic operator table)
Often, you have to compare two values to make some sort of determination of what to do next. These comparisons can grow to be quite complex, but you will, of course, start with the basics. The rationale behind these operators should be fairly understandable if you can avoid getting bogged down in the symbols.
The most basic and obvious comparison operator is the equals operator (==). This operator can compare two values, and determine if they are equal. The result of any comparison, including this one, is true or false.
Here is a very simple equality comparison:
mugs == 10
If the value of the variable mugs is 10, and thus equal to the literal value 10, then the above comparison will yield a true result. If mugs refers to any value other than 10, the result will be false. This result is most commonly used to direct the flow of the program, or to generate a condition-specific action (detailed more later).
Similarly, you could use the not equals (!=) comparison operator.
mugs != 10
Now, this is where you might get confused. The above will again compare the value of mugs with the literal value 10. However, this time we asked if they were "not equal." Therefore, if mugs is 5, then the above comparison will yield a true result. If mugs is 10, then the above will be false.
Two other common comparison operators are greater-than ( > ) and less-than ( < ). They are used in the following manners:
mugs > 10
If mugs is a value greater than (but not including) 10, the above yields true; otherwise it yields false.
mugs < 10
If mugs is a value less than (but not including) 10, the above yields true; otherwise it yields false.
Lastly, a pair of comparison operators are inclusive of the tested value--greater than or equal to ( >= ) and less than or equal to ( <= ):
mugs >= 10
mugs <= 10
These work the same way as the > and < operators, except they do include the tested value (10, in our example). Note, therefore, that if the value of mugs is 10, then both comparisons above would yield true.
Any of the previously mentioned folks who stayed awake in algebra class may recall that horrific week spent learning "logic." The magic words of a logician are AND, OR, and NOT. This makes for less than stimulating dinner date conversation, but it has many uses in JavaScript programs.
Logical operators are quite similar in usage to comparison operators. They also sort of "compare" two values, and provide a true or false result. The major difference in practice is that the logical operators usually "compare" comparison operators. What?? Once again, some examples are in order.
The && operator is given two comparisons, and if both are true in and of themselves, then the && operator returns a true. Try it this way:
( mugs > 5 ) && ( price < 10 )
The above first evaluates the comparison mugs > 5. This will either be true or false. Then, price < 10 is evaluated. That will either be true or false. If the first comparison is true AND the second comparison is true, then the logical operation will yield true. If either or both comparisons are false, the whole result is false.
It helps a lot to think of these logical comparisons in the context of an English sentence. We use them exactly the same way in verbal language: "If your father comes home early AND my paycheck cleared, we will go out for dinner." The example sentence contained both a logical comparison and a resulting action--for now, as far as JavaScript goes, just consider the logical comparison. The resulting actions will come later.
The OR operator is less finicky than the AND operator. It asks that only one of the two comparisons be true to return a true for the whole logical comparison. For example:
( mugs > 5 ) || ( price < 10 )
Just as with the && operator, both comparisons above are evaluated. If either is true, then the OR operator returns a true. Of course, if both are true, then a true is still returned. Only if both comparisons yield false results will the || operator yield a false result.
English example: "If your father comes home early OR my paycheck cleared, we'll go out for dinner." Only one condition needs to be satisfied for the family to chow down, in this case.
This one is twisted. The NOT operator is a unary operator, and, therefore, takes only one operand. That operand is often a comparison operator: the negation of the comparison is returned. Try selling that on a t-shirt! To explain from another angle, if the operand is true, then a ! operation on it will result in false. And vice versa.
In the following example, let's assume that mugs holds the value 5.
!(mugs == 5)
Above, mugs == 5 results in true, because it is true. However, it's included in a NOT operation, and thus the result of the whole phrase above is false. Of course, if you're clever, you might realize that the comparison (mugs != 5) would return the same result as !(mugs == 5) (that is, false). This is correct, and, therefore, in many cases, the NOT operator is unnecessary, because the same evaluation can be made with a comparison operator. However, programmers tend to like NOT operators because they often result in more compact code (although not in the previous example, where the comparison operator is, in fact, shorter).
You've reached the last of the operators. Whew. String operators are intended to work with string values, which you should recall are not numerals or arithmetic expressions. The comparison operators can be used with strings, as well. Since strings are not numerals, how these work requires a little explanation.
Checking for equality between two strings is fairly straightforward. Suppose you supply the following test (use literals for clarity, although in many cases you'd be using variable names):
"dogs" == "cats"
Clearly, the two strings are not equal--that is, the same, and so the comparison has a false result. For two strings to pass an equality test, they have to be exactly the same, character for character.
However, "dogs" cannot be greater than "cats" (depends who you ask!), so
"dogs" > "cats"
is simply nonsensical to JavaScript. The same applies to the <, >=, and <= operators. Of course, the "not equal" != operator could apply to two strings.
The exception to the above is if the strings represent possible numerals. Let's suppose the string in question is "54". In this case, JavaScript will attempt to convert the string to a numeral for comparison purposes (remember: strings cannot actually be compared to numbers, but JavaScript automatically tries to convert the string to a number). Therefore,
"54" > "12"
does make sense to JavaScript and is exactly the same as 54 > 12. But JavaScript can perform this conversion only if the string contains only numerals; "dog54" would not be converted to a numeral, and thus the above comparison would again be nonsensical and generate an error, or unpredictable results.
Lastly, strings can be concatenated with the + operator, or the += assignment operator. Concatenation is the process of combining multiple strings to yield one new, bigger string. You may want to construct a message for the user, tailored to be appropriate for varying conditions. For example,
"dogs " + "are cute"
would yield the string "dogs are cute" (note the space in the above, such that the words "dogs" and "are" are not directly smooshed together). Also, if you had previously assigned "dogs " to the variable named phrase, then
phrase += "are cute"
would assign the entire string "dogs are cute" to the variable named phrase.
Programming types throw around the term expressions. In a sense, by now, you're already familiar with what an expression is, but I haven't explicitly defined it yet. I wanted to keep some suspense in this tale, after all.
An expression, in programming circles, is any "phrase" of program code that represents one evaluation, result, or assignment. You've used a variety of expressions already so far:
mugs = 5
(price > 10)
There is no critical need for a specific definition of an expression; it's just a term that programmers use to refer to these little portions of code. Every little segment covered in examples thus far is an expression. There is one sort of JavaScript that's worth special note, though.
A conditional expression is basically a shorthand way to assign a value to a variable based on the results of a certain condition. A conditional expression looks like this:
(condition) ? valuetrue : valuefalse
If the condition is true, then the resulting value is whatever is specified in the position where valuetrue is above; if the condition is false, the value returned is whatever is positioned where valuefalse is above. A common use for this sort of conditional expression is in an assignment operation, such that a variable is assigned the result of the above expression. Clearer example: Imagine that you include a bonus gift-a pencil-with all mug orders fewer than 10, but you include a teddy bear with all orders of 10 mugs or more. You can use the conditional expression to make this determination as follows:
bonus = (mugs >= 10) ? "teddy" : "pencil"
The variable bonus will be assigned a string value of "teddy" if there are 10 or more mug orders, or "pencil" on fewer than 10 orders.
- Operators serve to bring values and/or variables together and yield new results.
- Arithmetic operators are used for basic math calculations, as well as incrementing and decrementing numeric variables.
- Comparison operators are used to evaluate specified cases, such as whether one variable has a greater value than another, or whether they are equal, and so forth.
- Logical operators evaluate comparisons against AND, OR, and NOT conditions to determine whether a series of conditions are true or false.
- String operators compare and/or concatenate strings of characters.
- Expressions are JavaScript "phrases," which yield assignments, evaluations, or results.



For comments or technical support for our books and software, select Talk to Us.
To order books, call us at 800-716-0044 or 317-228-4366.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.