javascript-precedencia-operadores

Operator Precedence in JavaScript

  • 4 min

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
Copied!

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
Copied!

Precedence Examples