JavaScript Operators Precedence Rules
By Flavio Copes
Learn how JavaScript operator precedence decides which operations run first, so an expression like 1 * 2 + 5 / 2 % 2 evaluates the way you expect.
Operator precedence decides which parts of an expression JavaScript evaluates first. Every operator has a priority level, and higher-priority operators run before lower-priority ones, regardless of where they appear in the line.
Every complex statement will introduce precedence problems.
Take this:
const a = 1 * 2 + 5 / 2 % 2
The result is 2.5, but why? What operations are executed first, and which need to wait?
Some operations have more precedence than the others. The precedence rules are listed in this table:
| Operator | Description |
|---|---|
- + ++ -- | unary operators, increment and decrement |
** | exponentiation |
* / % | multiply/divide |
+ - | addition/subtraction |
= += -= *= /= %= **= | assignments |
Operations on the same level (like + and -) are executed in the order they are found, from left to right.
Following this table, we can solve this calculation:
const a = 1 * 2 + 5 / 2 % 2
const a = 2 + 5 / 2 % 2
const a = 2 + 2.5 % 2
const a = 2 + 0.5
const a = 2.5
*, / and % all sit on the same level, so they run left to right: first 1 * 2, then 5 / 2, then the remainder. The addition has lower precedence, so it waits until the end.
Parentheses win over everything
You don’t have to memorize the table. Parentheses have the highest priority, so you can force the order you want:
const a = 1 * (2 + 5) / 2 % 2
// 1 * 7 / 2 % 2
// 7 / 2 % 2
// 3.5 % 2
// 1.5
My advice is to use parentheses in any expression that mixes operators. The next person reading the code (often you, months later) won’t have to run the precedence table in their head.
The exponentiation exception
Most operators on the same level run left to right. Exponentiation is the exception: it runs right to left.
2 ** 3 ** 2 // 512
This evaluates 3 ** 2 first, giving 2 ** 9, which is 512. If you expected (2 ** 3) ** 2, which is 64, you got a surprise. Assignment operators are also right to left, which is why a = b = 5 assigns 5 to both.
A common pitfall with strings
The + operator also concatenates strings, and left-to-right evaluation can bite you:
console.log('The result is ' + 1 + 2)
// The result is 12
The first + joins the string and 1, producing the string 'The result is 1'. The second + then appends '2'. The numbers never get added together.
The fix, once again, is parentheses:
console.log('The result is ' + (1 + 2))
// The result is 3Related posts about js: