Plenty of π
Module 3: Operators and User Interaction
Operator Precedence and Associativity

Operator Precedence: Determines the order in which operators are evaluated in an expression with multiple operators. For example, multiplication and division have higher precedence than addition and subtraction.

let result = 10 + 5 * 2; // 5 * 2 is evaluated first (10), then 10 + 10
console.log(result);    // Output: 20

You can use parentheses () to override the default precedence and force a specific order of evaluation.

let result2 = (10 + 5) * 2; // 10 + 5 is evaluated first (15), then 15 * 2
console.log(result2);     // Output: 30

Refer to the MDN documentation for a full list of JavaScript operator precedence: MDN Operator Precedence

Operator Associativity: Determines the order in which operators of the same precedence are evaluated. Most operators are left-to-right associative.

  • Left-to-right: a - b - c is evaluated as (a - b) - c.
  • Right-to-left: Assignment operators (=, +=) and the exponentiation operator (**) are right-to-left associative. a = b = 5; is evaluated as a = (b = 5); (so b becomes 5, then a becomes 5). 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2), which is 2 ** 9 = 512 (not (2 ** 3) ** 2 = 8 ** 2 = 64).

Understanding precedence and associativity is crucial for writing correct and predictable code.