Language: EN

javascript-precedencia-operadores

Operator Precedence in JavaScript

The precedence of operators 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, multiplication is performed before addition because the multiplication operator has a higher precedence than the addition operator.

Operator Precedence Table in JavaScript

Here is a table with the most common operators in JavaScript, ordered by their precedence, from highest to lowest:

PrecedenceOperatorDescription
1()Grouping
2. [] ()Property access and method calls
3++ -- + - ! ~Unary (pre-increment, pre-decrement, etc.)
4**Exponentiation
5* / %Multiplication, division, and modulus
6+ -Addition and subtraction
7<< >> >>>Bitwise left/right shift
8< <= > >=Comparison
9== != === !==Equality and inequality
10&Bitwise AND
11^Bitwise XOR
12|Bitwise OR
13&&Logical AND
14||Logical OR
15? :Ternary operator
16= += -= *= /= %= <<= >>= >>>= &= ^= |=Assignment
17,Comma operator

That is, those higher up in the table are evaluated before those below it.

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 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 found, they are evaluated 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 (which means they are evaluated 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

Examples of Precedence in JavaScript

:::::::