Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Understanding Expressions and Operators

In the definition of the Average function in the previous example, you used this statement to average the four numbers:

result = (a + b + c + d) / 4;

The portion of this statement to the right of the equal sign is called an expression: a combination of variables and values that the JavaScript interpreter can evaluate to a single value. The characters that are used to combine these values, such as + and /, are called operators.

Using JavaScript Operators

You've already used some operators, such as the + sign (addition) and the / sign (division) in the Average function example. Table 4.1 lists some of the most important operators you can use in JavaScript expressions.

Table 4.1. Common JavaScript Operators

Operator Description Example
+ Concatenate (combine) strings message="this is" + " a test";
+ Add result = 5 + 7;
- Subtract score = score - 1;
* Multiply total = quantity * price;
/ Divide average = sum / 4;
% Modulo (remainder) remainder = sum % 4;
++ Increment tries++;
-- Decrement total--;

You'll learn more about the increment and decrement operators later in this hour. There are also many other operators used in conditional statements—you'll learn about these in Hour 6, "Testing and Comparing Values."

Operator Precedence

When you use more than one operator in an expression, JavaScript uses rules of operator precedence to decide how to calculate the value. Table 4.1 above lists the operators from lowest to highest precedence, and operators with highest precedence are evaluated first. For example, consider this statement:

result = 4 + 5 * 3;

If you try to calculate this result, there are two ways to do it. You could multiply 5 * 3 first and then add 4 (result: 19) or add 4 + 5 first and then multiply by 3 (result: 27). JavaScript solves this dilemma by following the precedence rules: since multiplication has a higher precedence than addition, it first multiplies 5 * 3 and then adds 4, producing a result of 19.

Sometimes operator precedence doesn't produce the result you want. For example, consider this statement:

result = a + b + c + d / 4;

This is similar to the calculation in the Average function earlier this hour. However, since JavaScript gives division a higher precedence than addition, it will divide the d variable by 4 before adding the other numbers, producing an incorrect result.

You can control precedence by using parentheses. Here's the working statement from the Average function:

result = (a + b + c + d) / 4;

The parentheses ensure that the four variables are added first, and then the sum is divided by four.

Share ThisShare This

Informit Network