Advanced freeCodeCamp • lecture-working-with-operator-behavior

How Does Operator Precedence Work?

Lesson Overview

Operator precedence in JavaScript determines the order in which operators are evaluated in an expression. When multiple operators are present, JavaScript evaluates them based on a predefined hierar...

Operator precedence in JavaScript determines the order in which operators are evaluated in an expression. When multiple operators are present, JavaScript evaluates them based on a predefined hierarchy—similar to the order of operations (PEMDAS) used in mathematics.

1. The Precedence Hierarchy

Operators with higher precedence are evaluated before those with lower precedence. For example, multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).

  • Example: 2 + 3 * 4
    • Because multiplication has higher precedence, JavaScript performs 3 * 4 first (getting 12) and then adds 2, resulting in 14.

2. Left-to-Right vs. Right-to-Left (Associativity)

When operators have the same level of precedence, JavaScript uses associativity to determine the direction of evaluation:

  • Left-to-Right: Most operators (like addition and subtraction) are left-associative. If you have 5 - 4 + 2, JavaScript evaluates it from left to right: (5 - 4) + 2, resulting in 3.
  • Right-to-Left: Some operators, such as assignment (=) or the exponentiation operator (**), are right-associative.

3. Using Parentheses

You can override the default precedence by wrapping expressions in parentheses (). Expressions inside parentheses are always evaluated first, regardless of the operators’ standard precedence levels. This is a best practice for making your code easier to read.

  • Example: (2 + 3) * 4
    • The parentheses force the addition to happen first, resulting in 5 * 4 = 20.

Summary

  • Precedence: Decides “who goes first” between different types of operators.
  • Associativity: Decides the direction of evaluation when operators have the same precedence.
  • Parentheses: Use them explicitly whenever you want to clarify or change the order of operations.