By Paul McFedries

Your JavaScript code will often use expressions that are blissfully simple: just one or two operands and a single operator. But, alas, “often” here doesn’t mean “mostly,” because many expressions you use will have a number of values and operators. In these more complex expressions, the order in which the calculations are performed becomes crucial.

For example, consider the expression 3+5*2. If you calculate from left to right, the answer you get is 16 (3+5 equals 8, and 8*2 equals 16). However, if you perform the multiplication first and then the addition, the result is 13 (5*2 equals 10, and 3+10 equals 13). In other words, a single expression can produce multiple answers depending on the order in which you perform the calculations.

To control this ordering problem, JavaScript evaluates an expression according to a predefined order of precedence. This order of precedence lets JavaScript calculate an expression unambiguously by determining which part of the expression it calculates first, which part second, and so on.

The order of precedence

The order of precedence that JavaScript uses is determined by the various expression operators. This table summarizes the complete order of precedence used by JavaScript.

The JavaScript Order of Precedence for Operators
Operator Operation Order of Precedence Order of Evaluation
++ Increment First R -> L
-- Decrement First R -> L
Negation First R -> L
! NOT First R -> L
*, /, % Multiplication, division, modulus Second L -> R
+, — Addition, subtraction Third L -> R
+ Concatenation Third L -> R
<, <= Less than, less than, or equal Fourth L -> R
>, >= Greater than, greater than, or equal Fourth L -> R
== Equal Fifth L -> R
!= Not equal Fifth L -> R
=== Identity Fifth L -> R
!== Non-identity Fifth L -> R
&& AND Sixth L -> R
|| OR Sixth L -> R
?: Ternary Seventh R -> L
= Assignment Eighth R -> L
+=, -=, and so on. Arithmetic assignment Eighth R -> L

For example, the table above tells you that JavaScript performs multiplication before addition. Therefore, the correct answer for the expression =3+5*2 (just discussed) is 13.

Notice, as well, that some operators in the table have the same order of precedence (for example, multiplication and division). Having the same precedence means that the order in which JavaScript evaluates these operators doesn’t matter. For example, consider the expression 5*10/2. If you perform the multiplication first, the answer you get is 25 (5*10 equals 50, and 50/2 equals 25). If you perform the division first, you also get an answer of 25 (10/2 equals 5, and 5*5 equals 25).

However, JavaScript does have a predefined order for these kinds of expressions, which is what the Order of Evaluation column tells you. A value of L -> R means that operations with the same order of precedence are evaluated from left-to-right; R -> L means the operations are evaluated from right-to-left.

Controlling the order of precedence

Sometimes you want to take control of the situation and override the order of precedence. That might seem like a decidedly odd thing to do, so perhaps an example is in order. As you probably know, you calculate the total cost of a retail item by multiplying the retail price by the tax rate, and then adding that result to the retail price:

Total Price = Retail Price + Retail Price * Tax Rate

However, what if you want to reverse this calculation? That is, suppose you know the final price of an item and, given the tax rate, you want to know the original (that is, pre-tax) price. Applying a bit of algebra to the preceding equation, it turns out that you can calculate the original price by dividing the total price by 1 plus the tax rate. So if the total price is $11.00 and the tax rate is 10%, then you divide 11 by 1.1 and get an answer of $10.00.

Okay, now let’s convert this calculation to JavaScript code. A first pass at the new equation might look something like this:

retailPrice = totalPrice / 1 + taxRate;

The following code implements this formula:

var totalPrice = 11.00;
var taxRate = .1;
var retailPrice = totalPrice / 1 + taxRate;
alert("The pre-tax price is " + retailPrice);
calculating pre-tax JavaScript
The result of our first stab at calculating the pre-tax cost of an item.

As you can see, the result is incorrect. What happened? Well, according to the rules of precedence, JavaScript performs division before addition, so the totalPrice value first is divided by 1 and then is added to the taxRate value, which isn’t the correct order.

To get the correct answer, you have to override the order of precedence so that the addition 1 + taxRate is performed first. You override precedence by surrounding that part of the expression with parentheses, as shown in the following code. Using this revised script, you get the correct answer.

var totalPrice = 11.00;
var taxRate = .1;
var retailPrice = totalPrice / (1 + taxRate);
alert("The pre-tax price is " + retailPrice);
revised script coding
The revised script calculates the pre-tax cost correctly.

One of the most common mistakes when using parentheses in expressions is to forget to close a parenthetic term with a right parenthesis. To make sure you’ve closed each parenthetic term, count all the left parentheses and count all the right parentheses. If these totals don’t match, you know you’ve left out a parenthesis.

In general, you can use parentheses to control the order that JavaScript uses to calculate expressions. Terms inside parentheses are always calculated first; terms outside parentheses are calculated sequentially (according to the order of precedence). To gain even more control over your expressions, you can place parentheses inside one another; this is called nesting parentheses, and JavaScript always evaluates the innermost set of parentheses first.

Using parentheses to determine the order of calculations allows you to gain full control over JavaScript expressions. This way, you can make sure that the answer given by an expression is the one you want.