CodeBlanks Logo Icon CodeBlanks

Operator precedence

JavaScript course · Beginner · Lesson 11/133

Learn how operation order is determined and how to change precedence with parentheses.

Operator precedence

When several operators meet in the same expression, JavaScript follows a precedence order: multiplication and division happen before addition and subtraction. Just like in math class.

For example, in 2 + 3 * 4 the 3 * 4 is computed first, then 2 is added; the result is 14. Multiplication has higher precedence than addition.

Changing precedence with parentheses

To control precedence yourself, you use parentheses. The expression inside parentheses is always computed first. If you write (2 + 3) * 4, first 2 + 3 = 5 is found, then 5 * 4 = 20 is produced.

Parentheses also help the reader: they make your intent clear. In a mixed expression, using parentheses prevents surprising results.

Exercise Average of three grades

grade1, grade2 and grade3 are already declared. Declare average; divide the sum of the three grades by three. Use parentheses.

Show example solution
const grade1 = 70;
const grade2 = 80;
const grade3 = 90;
// Average of three grades
let average = (grade1 + grade2 + grade3) / 3;

Test yourself

  1. What is the result of 2 + 3 * 4?

    console.log(2 + 3 * 4);
    • 14
    • 20
    • 11
    • 9
    Show answer

    14 — Correct. First 3 * 4 = 12, then 2 + 12 = 14.

  2. Reorder with parentheses

    const result = ____2 + 3) * 4;
    console.log(result);
    Show answer
    const result = (2 + 3) * 4;
    console.log(result);
  3. Match the precedence level

    (
    Highest precedence
    *
    Medium high precedence
    +
    Medium low precedence
    =
    Lowest precedence

All lessons in Beginner