javascript

Operator Precedence

Learn how JavaScript's operator precedence rules determine the order of calculations in your code. Understand why some operations happen first and use parentheses for accurate results.

9 min read 8 sections Tutorial
Share

When you write code that does math, JavaScript needs to know which part of the math to do first. This order is called operator precedence. Understanding it helps you write code that calculates correctly every time.

Operator Precedence

Operator Precedence

When you write code that does math, JavaScript needs to know which part of the math to do first. This order is called operator precedence. Understanding it helps you write code that calculates correctly every time. It ensures your programs perform calculations exactly as you intend.

What is Operator Precedence?

Operator precedence is a set of rules that tells JavaScript the order in which to perform mathematical operations or evaluate expressions.

Default Order

JavaScript has built-in rules that decide which operations (like multiplication or addition) are done first.

Common Operators

Different types of operators, like arithmetic (+, -, *, /) or assignment (=), have different priority levels.

Using Parentheses

You can use parentheses () to change the default order and make certain parts of your math happen first.

Accurate Results

Knowing precedence ensures your calculations are always correct, preventing unexpected errors in your programs.

Understanding the Order of Operations

Getting Started

Understanding the Order of Operations

You might remember 'PEMDAS' or 'BODMAS' from school math. These are rules like 'multiplication before addition'. JavaScript uses very similar rules. It means some math operations are always done before others.

javascript
1let result1 = 5 + 2 * 3; // Multiplication happens before addition
2console.log(result1); // What do you think this will be? (2 * 3 = 6, then 5 + 6 = 11)
3
4let result2 = (5 + 2) * 3; // Parentheses change the order
5console.log(result2); // Now, addition happens first (5 + 2 = 7, then 7 * 3 = 21)

The #1 Beginner Mistake

A common mistake is forgetting that multiplication and division happen before addition and subtraction. This can lead to your code giving you the wrong answer. Always think about the order of operations.

How Precedence Rules Work

How Precedence Rules Work

JavaScript has a list of all its operators. Each operator has a 'priority level'. Operators with higher priority are executed first. If two operators have the same priority, JavaScript looks at their 'associativity' to decide the order.

javascript
1let value = 10 / 2 + 3 * 4 - 1; // Division and multiplication have higher precedence than addition and subtraction
2
3// Step 1: 10 / 2 = 5
4// Step 2: 3 * 4 = 12
5// Expression becomes: 5 + 12 - 1
6
7// Step 3: 5 + 12 = 17 (Addition and subtraction have same precedence, evaluated left-to-right)
8// Step 4: 17 - 1 = 16
9
10console.log(value); // This will output 16
✗ BadWrong (Misunderstood Precedence)
let incorrectResult = 10 + 5 / 5;
// A beginner might think: (10 + 5) = 15, then 15 / 5 = 3
// But division happens first!
console.log(incorrectResult); // Actual output: 11 (5 / 5 = 1, then 10 + 1 = 11)
✓ GoodCorrect (Applying Precedence)
let correctResult = 10 + (5 / 5);
// Here, we explicitly use parentheses for clarity, though not strictly needed.
// Division (5 / 5) = 1, then addition (10 + 1) = 11.
console.log(correctResult); // Actual output: 11

Using Parentheses to Control Order

Using Parentheses to Control Order

Sometimes, the default precedence is not what you want. Or, you want to make your code super clear for others (or your future self!). You can use parentheses () to force JavaScript to do certain operations first. Anything inside parentheses is always evaluated before anything outside them.

Default Precedence (Multiplication First)
let totalCost = 10 + 2 * 5; // 2 * 5 = 10, then 10 + 10 = 20
console.log(totalCost); // Outputs: 20
VS
Parentheses (Addition First)
let totalCostWithDiscount = (10 + 2) * 5; // (10 + 2) = 12, then 12 * 5 = 60
console.log(totalCostWithDiscount); // Outputs: 60

When to Use Parentheses

Always use parentheses () if you are unsure about the order, or if it makes your code easier to read. Even if the default precedence would give the same result, parentheses add clarity and prevent mistakes.

Real-World Examples of Operator Precedence

Real-World Examples of Operator Precedence

Operator precedence is crucial in real applications. Imagine calculating prices with discounts, taxes, or complex formulas. If the order of operations is wrong, your financial calculations will be incorrect. This can lead to serious problems in e-commerce or data analysis.

1

Calculate Item Price with Tax

First, let's define the base price of an item and the tax rate. We want to add the tax after calculating it on the item's price.

javascript
1let itemPrice = 100; // The base price of an item
2let taxRate = 0.05; // 5% tax rate (as a decimal)
2

Apply Tax Correctly

To get the total price, we first calculate the tax amount (itemPrice * taxRate), then add it to the itemPrice. Multiplication has higher precedence, so this works naturally.

javascript
1let taxAmount = itemPrice * taxRate; // Calculates 100 * 0.05 = 5
2let totalPrice = itemPrice + taxAmount; // Then 100 + 5 = 105
3console.log(`Total Price (with tax): $${totalPrice}`); // Outputs: Total Price (with tax): $105
3

Calculate Discounted Price with Tax

Now, let's add a discount. We want to apply the discount before calculating tax. This means the discount calculation should happen first, perhaps using parentheses.

javascript
1let discount = 10; // $10 discount
2
3// Apply discount first, then calculate tax on the discounted price
4let finalPrice = (itemPrice - discount) * (1 + taxRate);
5// (100 - 10) = 90
6// 90 * (1 + 0.05) = 90 * 1.05 = 94.5
7
8console.log(`Final Price (after discount and tax): $${finalPrice}`); // Outputs: Final Price (after discount and tax): $94.5

What Goes Wrong?

If you ignore precedence, your calculations will be wrong. For example, if you tried itemPrice - discount * (1 + taxRate), JavaScript would calculate discount * (1 + taxRate) first, leading to a completely incorrect total. This can cause financial errors in real-world applications.

Common JavaScript Operators and Their Precedence

Common JavaScript Operators and Their Precedence

CategoryOperatorsDescriptionPrecedence (Higher = First)
Grouping()Overrides default precedence, evaluates inner expression first.Highest
Unary++, --, !, typeofOperators that work on a single value (e.g., increment, logical NOT).High
Multiplicative*, /, %Multiplication, division, and remainder.Medium-High
Additive+, -Addition and subtraction.Medium
Assignment=, +=, -=, etc.Assigns a value to a variable.Lowest

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

What is the value of result in this JavaScript code: let result = 4 + 6 / 2;?

Quick Check

How can you force addition to happen before multiplication in 5 * 2 + 3?

Quick Check

Which operation has higher precedence?

Quick Check

If x = 10, what is the value of y after let y = x - 2 * 3;?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Precedence Rules — JavaScript uses rules to decide the order of operations in your math.
  • 2Higher Priority — Operations like multiplication (*) and division (/) happen before addition (+) and subtraction (-).
  • 3Parentheses () — Use parentheses to explicitly control the order of evaluation, making sure certain parts are calculated first.
  • 4Clarity is Key — Even if not strictly necessary, using parentheses makes your code easier for others (and you) to understand.
  • 5Associativity — This rule determines the order when operators have the same precedence (e.g., 10 - 5 - 2 is (10 - 5) - 2).
  • 6All Operators — Precedence applies to all JavaScript operators, not just math operations.
  • 7Avoid Mistakes — Misunderstanding precedence is a common source of bugs that lead to incorrect calculations.
  • 8Debugging — If your math is wrong, check your operator precedence first, then variable values.
  • 9Complex Expressions — Break down complex calculations into smaller, parenthesized parts for better readability and correctness.
  • 10Practice — The more you write code with calculations, the more natural operator precedence will become.

Arithmetic Operators

Explore all the different arithmetic operators like modulus (%) and exponentiation (**).

Assignment Operators

Learn about operators that assign values, like += and -=, and their precedence.

Comparison Operators

Understand how operators like ==, ===, !=, and !== compare values in your code.

Logical Operators

Discover && (AND), || (OR), and ! (NOT) and how they combine true/false conditions.

Great Job!

You've successfully learned about operator precedence in JavaScript! You now understand why some math operations happen before others and how to use parentheses to control the order. This is a fundamental skill for writing accurate and reliable code. Keep practicing, and your calculations will always be correct!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning