Skip to content

Operator Precedence Error

Quick summary

Your expression gives the wrong result because operators are evaluated in an order you did not intend.

Why this happens

  • Missing parentheses to control evaluation order

  • Assuming left-to-right evaluation for all operators

  • Mixing operators with different precedence (e.g., + and *)

Minimal example

✗ Broken code
let avg = 10 + 20 + 30 / 3; // 10 + 20 + 10 = 40, not 20
console.log(avg);
✓ Fixed code
let avg = (10 + 20 + 30) / 3; // 60 / 3 = 20
console.log(avg);

Division has higher precedence than addition, so 30/3=10 is computed first, then 10+20+10=40. Parentheses force the addition first: (10+20+30)/3=20.

How to diagnose

  • Print the intermediate values to see what is actually computed

  • Check the operator precedence table for your language

  • Add parentheses to make the intended order explicit

How to fix

  • Add parentheses to enforce the desired evaluation order

  • Break complex expressions into smaller, named steps

  • Use a calculator to verify the expected result

How to prevent

  • Use parentheses generously in complex expressions

  • Break long expressions into intermediate variables

Related Resources

Related Glossary

Related Lessons

← Back to language