Chapter 6:
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 in order to generate new and improved (or at least useful) data. I guarantee this will be fun. If it’s not, 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.

Let's Play Operation!

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 techno-talk, the values used with an operator are called operands. Thus, consider the following:

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:

The asterisk (*) is the operator for "multiply." JavaScript offers a wide array of arithmetic operators, which you can use with your values, whether they are 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

What It Does
modulus (returns the remainder of a division)
One Lump or Two? Binary and Unary Operators

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, which will be a variable. There are three unary operators in JavaScript to know: increment, decrement, and negation. Here's an example of each.

Unary Increment ++ 

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 further detailed later in this chapter) use this in an assignment:

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. Because the value of mugs was increased after mugs’ value was assigned to sales, sales does not gain the benefit of the increment. This is as opposed to

where 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 when you mean the other, your later calculations may be off by 1.

Unary Decrement ––

This operator works just like 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).

Unary Negation –

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, –mugs would return the value –5. Of course, if mugs was already –5, the unary negation operator would return the value 5 (because the negation of –5 is 5).

No More Math, But More Operators

There are several other varieties of operators besides arithmetic. Each one works by relating two or more variables 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.

Assignment Operators

You've already encountered one form of assignment operator: the equal sign (=). This is the most basic and common assignment operator and, as you’ve learned, it 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:

In longhand, using the aforementioned arithmetic operators, the above could also be written like this:

One common application of this technique is updating a running total. Perhaps you're keeping track of cumulative gross profit and want to keep adding new purchase orders to that gross. If the current value of total was 10, and price was 5, 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)
Comparison Operators

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:

If the value of the variable mugs is 10, and thus equal to the literal value 10, 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 (which you’ll learn more about later).

Similarly, you could use the not equals (!=) comparison operator, as in this example:

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, the above comparison will yield a true result. If mugs is 10, the above will be false.

Two other common comparison operators are greater than (>) and less than (<). They are used in the following manner:

mugs > 10
mugs < 10
If mugs is a value greater than (but not including) 10, the first statement above yields true; otherwise it yields false. Similarly, if mugs is a value less than (but not including) 10, the second statement above yields true; otherwise it yields false.

Lastly, a pair of comparison operators is inclusive of the tested value: greater than or equal to (>=) and less than or equal to (<=). Here are examples of their use:

mugs >= 10
mugs <= 10
These work the same as the > and < operators, except that they do include the tested value (10, in our example). Note, therefore, that if the value of mugs is 10, both comparisons above would yield true.

Not Just for Vulcans Anymore: Logical Operators

Some 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. Although this makes for less-than-stimulating dinner date conversation, 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.

&& (a.k.a the AND Operator)

The && operator looks at two comparisons, and if each is true in and of itself, the && operator returns a true. Try it this way:

The above statement first evaluates the comparison mugs > 5. That will be either true or false. Then it evaluates price < 10. That will also be either true or false. Finally, if the first comparison is true AND the second comparison is true, 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. But for now, as far as JavaScript goes, just consider the logical comparison. The resulting actions will come later.

|| (a.k.a the OR Operator)

The OR operator is less finicky than the AND operator. It requires that only one of the two comparisons be true in order for it 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, the OR operator returns a true. Of course, if both are true, it still returns a true. Only if both comparisons yield false results will the || operator yield a false result.

Take this English sentence for 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.

! (a.k.a the NOT Operator)

This one is twisted. The NOT operator is a unary operator and, therefore, takes only one operand. That operand is often a comparison operator, in which case the negation of the comparison is returned. Try selling that on a T-shirt! To explain from another angle, if the operand is true, a ! operation on it will result in false. And vice versa.

In the following example, let's assume that mugs holds the value 5.

Above, mugs == 5 results in true because it is true. However, because it's included in a NOT operation, 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 result would be 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).

String Operators: The Loom of JavaScript

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. In addition, the comparison operators can be used with strings. Because strings are not numerals, how string operators 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):

Clearly, the two strings are not equal (the same), 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, because "dogs" cannot be greater than "cats" (depending who you ask!), the statement "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 rule that strings cannot be compared with greater than and less than 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 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, the line

would yield the string "dogs are cute" (note the space in the above, which prevents the words "dogs" and "are" from being directly smooshed together). Also, if you had previously assigned "dogs " to the variable named phrase, this line

would assign the entire string "dogs are cute" to the variable named phrase.

Full of Expressions

Programming types like to throw around the term “expressions.” In a sense, by now, you're already familiar with what an expression is, even though 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 already used a variety of expressions so far, such as:

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:

If the condition is true, the resulting value is whatever is specified in the position where valueiftrue is above; if the condition is false, the value returned is whatever is positioned where valueiffalse is above. A common use for this sort of conditional expression is in an assignment operation, in which a variable is assigned the result of the above expression. For a clearer example, imagine that you include a bonus gift—a pencil—with all mug orders fewer than 10, and you include a teddy bear with all orders of 10 mugs or more. You can use the following conditional expression to make this determination:

The variable bonus will be assigned a string value of "teddy" for orders of 10 or more mugs, or it will be assigned "pencil" on orders for fewer than 10 mugs.

The Least You Need to Know

Previous Chapter Next Chapter

Beginning of ChapterTable of ContentsBook Home PageQue Home Page

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.

1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.