Operator Precedence
Second in importance to understanding that every expression resolves to a value is
understanding operator precedence: it is a vital step to following how a JavaScript
program works.
Now that we’ve covered arithmetic operators, we’re going to pause our discussion of
JavaScript’s many operators and review operator precedence—if you’ve had an ele‐
mentary education, you’ve already been exposed to operator precedence, even if you
aren’t aware of it.
See if you remember enough from elementary school to solve this problem (I apolo‐
gize in advance to those who suffer from math anxiety):
8 ÷ 2 + 3 × 4 × 2 − 1
If you answered 25, you correctly applied operator precedence. You knew to start
inside the parentheses, then move on to multiplication and division, then finish with
addition and subtraction.
JavaScript uses a similar set of rules to determine how to evaluate any expression—
not just arithmetic expressions. You’ll be pleased to know that arithmetic expressions
in JavaScript use the same order of operations you learned in elementary school—
perhaps with the aid of the mnemonic “PEMDAS” or “Please Excuse My Dear Aunt
Sally.”
In JavaScript, there are many more operators than just arithmetic ones, so the bad
news is that you have a much larger order to memorize. The good news is that, just
like in mathematics, parentheses trump everything: if you’re ever unsure about the
order of operations for a given expression, you can always put parentheses around
the operations you want to happen first.
Currently, JavaScript has 56 operators grouped into 19 precedence levels. Operators
with a higher precedence are performed before operators with a lower precedence.
Although I have gradually memorized this table over the years (without making a
conscious effort to do so), I still sometimes consult it to refresh my memory or see
where new language features fit into the precedence levels. See
for the
operator precedence table.
Operators at the same precedence level are either evaluated right to left or left to right.
For example, multiplication and division have the same precedence level (14) and are
evaluated left to right, and assignment operators (precedence level 3) are evaluated
right to left. Armed with that knowledge, we can evaluate the order of operations in
this example:
84 | Chapter 5: Expressions and Operators