Operator precedence defines the order in which operators are evaluated when there are multiple operators in an expression.
Logically, operators with higher precedence are evaluated before operators with lower precedence.
For example, in the expression 3 + 4 * 5, the multiplication is performed before the addition because the multiplication operator has a higher precedence than the addition operator.
If you want to learn more, check out the Introduction to Programming Course
That is, those higher up in that table are evaluated before those below.
Associativity
Associativity defines the order in which operators with the same precedence are evaluated. It can be left-to-right or right-to-left.
For example, in the expression 5 - 3 + 2, the operation is performed from left to right because subtraction and addition have the same precedence.
Most operators in JavaScript have left-to-right associativity. That is, if multiple operators of the same type are encountered, they are evaluated from left to right.
const resultado = 5 - 3 + 2;
// it evaluates as
const resultado = (5 - 3) + 2; // 4
But some operators have right-to-left associativity (meaning they are evaluated from right to left). The two odd ducks are:
- The assignment operator (
=) - The exponentiation operator (
**).
let a, b, c;
a = b = c = 10;
// It evaluates as
a = (b = (c = 10))
console.log(a); // and all are 10 and happy
Precedence Examples
Arithmetic Operators
Consider the expression:
const resultado = 3 + 4 * 5;
Because the * operator has a higher precedence than the + operator, the multiplication is performed before the addition:
const resultado = 3 + (4 * 5); // 3 + 20 = 23
Unary and Binary Operators
In the expression:
const valor = -3 ** 2;
The ** operator has a higher precedence than the - operator, so the expression is evaluated as:
const valor = -(3 ** 2); // -(9) = -9
Comparison and Logical Operators
Consider the expression:
const esValido = 5 < 10 && 10 < 15;
The && operators have lower precedence than the comparison operators <. The expression is evaluated as:
const esValido = (5 < 10) && (10 < 15); // true && true = true
Ternary Operator
The ternary operator has a lower precedence than arithmetic operators, so it is evaluated after arithmetic operations:
const resultado = 10 + 5 > 10 ? 'Greater' : 'Less';
Here, the expression 10 + 5 > 10 is evaluated first, and then the ternary operator is applied:
const resultado = (10 + 5 > 10) ? 'Greater' : 'Less'; // 'Greater'
