JavaScript and TypeScript course ยท Module 1: JavaScript Basics

Operator Precedence

9 min read ยท
In this lesson7

In Jurassic Park, security protocols must be strictly followed and executed in the proper order. For example, before opening the gate to the Tyrannosaurus enclosure, you must ensure that all other doors are closed and that employees are in safe zones. The order of these actions is crucial.

Similarly in JavaScript, operators have their precedence, which determines the order of their execution in expressions. Understanding this hierarchy is essential for creating correct and predictable expressions.

What is Operator Precedence?

Operator precedence is a rule that determines the order in which operators are executed in complex expressions. Operators with higher precedence are executed before operators with lower precedence.

Imagine that in Jurassic Park we have a task list with different priorities:

  1. Highest priority: Check power supply to electric fences
  2. Medium priority: Check food supply for dinosaurs
  3. Low priority: Update information for visitors

Similarly, JavaScript has its own hierarchy of operator precedence.

Operator Precedence Table

Below is a simplified table of operator precedence in JavaScript, from highest to lowest:

PrecedenceCategoryOperators
19Grouping( ... )
18Property access and array elements. [] ?.
17Function call... ( ... )
16Postfix operators++ --
15Prefix operators! ~ + - ++ -- typeof void delete
14Exponentiation**
13Multiplication, division, modulo* / %
12Addition, subtraction+ -
11Bitwise shift<< >> >>>
10Comparisons (inequalities)< > <= >= instanceof in
9Equality== != === !==
8Bitwise AND&
7Bitwise XOR^
6Bitwise OR|
5Logical AND&&
4Logical OR||
3Nullish coalescing??
2Conditional operator? :
1Assignment= += -= *= /= %= <<= >>= >>>= &= ^= |= **=
0Comma operator,

Jurassic Park Examples

Let's see how operator precedence works in practice, using examples from daily work in Jurassic Park:

Example 1: Arithmetic Operations

// Calculating the amount of food needed for dinosaurs

let smallCarnivores = 5;
let mediumCarnivores = 3;
let largeCarnivores = 2;

let dailyConsumptionSmall = 50; // kg
let dailyConsumptionMedium = 150; // kg
let dailyConsumptionLarge = 300; // kg

// Without parentheses - operator precedence determines the order
let totalFood = smallCarnivores * dailyConsumptionSmall + mediumCarnivores * dailyConsumptionMedium + largeCarnivores * dailyConsumptionLarge;

console.log(totalFood); // 1300 kg

// Multiplication (*) has higher precedence than addition (+), so the above expression is equivalent to:
let totalFood2 = (smallCarnivores * dailyConsumptionSmall) + (mediumCarnivores * dailyConsumptionMedium) + (largeCarnivores * dailyConsumptionLarge);

console.log(totalFood2); // 1300 kg (same result)

Example 2: Logical and Comparison Operators

// Checking conditions for opening an enclosure to visitors

let airTemperature = 28; // degrees Celsius
let humidity = 60; // percent
let windSpeed = 15; // km/h
let threatLevel = 2; // scale 1-5
let availableStaff = 5; // number of employees
let requiredStaff = 3; // minimum number

// Complex condition without parentheses
let openEnclosure = airTemperature > 20 && humidity < 80 && windSpeed < 20 || threatLevel <= 2 && availableStaff >= requiredStaff;

// How does JavaScript interpret this? The && operator has higher precedence than ||
// The above expression is equivalent to:
let openEnclosure2 = ((airTemperature > 20 && humidity < 80 && windSpeed < 20) || (threatLevel <= 2 && availableStaff >= requiredStaff));

console.log(openEnclosure); // true
console.log(openEnclosure2); // true (same result)

Example 3: Conditional Operator and Assignment

// Determining security status for different dinosaur species

let species = "Velociraptor";
let aggression = 4; // scale 1-5
let fenceHeight = 5; // meters

// Complex expression with conditional operator and assignment
let securityStatus = species === "Tyrannosaurus" || species === "Spinosaurus" || aggression >= 4 ? "High" : aggression >= 3 ? "Medium" : "Low";

console.log(securityStatus); // "High" (for Velociraptor with aggression 4)

// More readable version with parentheses showing the actual evaluation order:
let securityStatus2 = (species === "Tyrannosaurus" || species === "Spinosaurus" || aggression >= 4) ? "High" : (aggression >= 3 ? "Medium" : "Low");

console.log(securityStatus2); // "High" (same result)

Example 4: Grouping (Highest Precedence)

// Calculating estimated dinosaur population after several generations

let initialPopulation = 2;
let reproductionRate = 3; // average number of offspring
let generations = 2;

// Calculation without parentheses
let estimatedPopulation1 = initialPopulation * reproductionRate ** generations;
console.log(estimatedPopulation1); // 18 (2 * 3^2 = 2 * 9 = 18)

// Changing the order using parentheses (grouping)
let estimatedPopulation2 = (initialPopulation * reproductionRate) ** generations;
console.log(estimatedPopulation2); // 36 ((2 * 3)^2 = 6^2 = 36)

Example 5: Combining Different Operators

// Supply calculator after delivery

let currentResources = 500; // kg
let weeklyDelivery = 200; // kg
let averageDailyConsumption = 50; // kg
let daysInWeek = 7;
let refrigeratorsWorking = true;
let maxStorageCapacity = 1000; // kg

// Complex calculator without explicit grouping
let newState = currentResources + weeklyDelivery - averageDailyConsumption * daysInWeek * (refrigeratorsWorking ? 1 : 1.5);

console.log(newState); // 350 kg (500 + 200 - 50 * 7 * 1)

// More readable version with parentheses showing the actual evaluation order:
let newState2 = currentResources + weeklyDelivery - (averageDailyConsumption * daysInWeek * (refrigeratorsWorking ? 1 : 1.5));

console.log(newState2); // 350 kg (same result)

// Check if the new state exceeds the storage capacity
let percentageState = newState / maxStorageCapacity * 100;
console.log(percentageState + "%"); // 35%

Recommendations for Using Parentheses

Although JavaScript has strictly defined operator precedence, using parentheses to explicitly define the order of operations has several advantages:

  1. Increases code readability - even if you know operator precedence, explicit parentheses make code more readable for you and others.

  2. Prevents errors - in complex expressions, it's easy to make mistakes related to the order of operations.

  3. Facilitates modification - if you later change an expression, parentheses can prevent unexpected changes in logic.

// Example of using parentheses for increased readability

// Less readable:
let isSafe = !fenceBroken && powerActive || emergencyMode && evacuationComplete;

// More readable with parentheses:
let isSafe2 = (!fenceBroken && powerActive) || (emergencyMode && evacuationComplete);

Operator Associativity

Besides precedence, an important characteristic of operators is their associativity, which determines the order of execution for operators of the same precedence:

  • Left-to-right associativity: most operators, e.g., +, -, *, /
  • Right-to-left associativity: some operators, e.g., =, **, +=, unary operators (!, ++, --)
// Example of left-to-right associativity
let a = 5 - 3 - 2;  // (5 - 3) - 2 = 0

// Example of right-to-left associativity
let b = 2;
let c = 3;
let d = 4;
let e = b = c = d; // b = (c = (d)) = 4
console.log(b, c, d, e); // 4, 4, 4, 4

// Exponentiation is also right-to-left associative
let f = 2 ** 3 ** 2; // 2 ** (3 ** 2) = 2 ** 9 = 512
let g = (2 ** 3) ** 2; // 8 ** 2 = 64
console.log(f, g); // 512, 64

Practical Tips from Jurassic Park

In Jurassic Park, ambiguity in security protocols can lead to catastrophic consequences. Similarly, ambiguous expressions in code can lead to unexpected results. Here are some tips:

  1. Use parentheses when combining different types of operators - especially when mixing arithmetic, logical, and conditional operators.

  2. Break complex expressions into simpler ones - for greater readability and easier debugging, you can assign intermediate results to variables.

// Instead of:
let result = a * b + c * d && e > f || g <= h;

// Better:
let part1 = a * b + c * d;
let part2 = e > f;
let part3 = g <= h;
let result = part1 && part2 || part3;
  1. Be careful with postfix and prefix operators - the ++ and -- operators can lead to unexpected results when used in complex expressions.
let dinosaurCount = 5;
let newCount = dinosaurCount++ * 2; // first uses value 5, then increments dinosaurCount to 6
console.log(newCount, dinosaurCount); // 10, 6

let cageCount = 5;
let newCageCount = ++cageCount * 2; // first increments cageCount to 6, then uses that value
console.log(newCageCount, cageCount); // 12, 6

Summary

Operator precedence in JavaScript, much like the task hierarchy in Jurassic Park, determines the order of operations. Knowledge of this hierarchy is crucial for writing correct and predictable code.

The most important things to remember:

  1. Grouping with parentheses has the highest precedence and allows controlling the order of operations.
  2. Arithmetic operators (*, /) have higher precedence than (+, -).
  3. Comparison operators (>, <, >=, <=) have higher precedence than equality operators (==, ===, !=, !==).
  4. Logical AND (&&) has higher precedence than OR (||).
  5. Assignment operators (=, +=, -=, etc.) have one of the lowest precedences.

Remember, when in doubt, it's always better to use parentheses for clarity - just as in Jurassic Park, where it's better to over-protect against unexpected situations than to risk unforeseen consequences.

In the next lesson, we will look at control structures - conditional statements that allow making decisions based on specific conditions - essential for managing such a complex undertaking as Jurassic Park.

Code for this lesson: index.js
// Operator precedence in JavaScript
// Order of operations

// === Arithmetic precedence ===
console.log("=== Arithmetic precedence ===");

// Multiplication before addition
console.log("2 + 3 * 4 =", 2 + 3 * 4);       // 14 (not 20!)
console.log("(2 + 3) * 4 =", (2 + 3) * 4);   // 20 (parentheses change the order)

// Exponentiation has higher precedence than multiplication
console.log("2 * 3 ** 2 =", 2 * 3 ** 2);       // 18 (not 36!)
console.log("(2 * 3) ** 2 =", (2 * 3) ** 2);   // 36

// === Logical precedence ===
console.log("\n=== Logical precedence ===");

// AND (&&) has higher precedence than OR (||)
let a = true, b = false, c = true;
console.log("true || false && false:", true || false && false); // true
// Equivalent: true || (false && false) -> true || false -> true

console.log("(true || false) && false:", (true || false) && false); // false

// === Comparison and logic ===
console.log("\n=== Combining comparison and logic ===");

let age = 25;
let weight = 7000;
let diet = "carnivore";

// Without parentheses - can be confusing
let dangerous = diet === "carnivore" && weight > 5000 || age > 30;
console.log("Without parentheses:", dangerous);

// With parentheses - clear and readable
let dangerousClear = (diet === "carnivore" && weight > 5000) || age > 30;
console.log("With parentheses:", dangerousClear);

// === Conditional operator (ternary) ===
console.log("\n=== Conditional operator ===");
let status = weight > 5000 ? "Large dinosaur" : "Small dinosaur";
console.log("Status:", status);

// Your task:
// 1. Calculate expressions with different precedences
// 2. Use parentheses to change the order of operations
// 3. Use the conditional operator (ternary)

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which logical operator has higher precedence in JavaScript?

  2. 2. How can you force a different order of operations than the default in JavaScript?

Hands-on tasks in the game

  • Vertical ordering

    Arrange operator categories from highest to lowest precedence:

  1. Question&& vs || Precedence
  2. QuestionGrouping with Parentheses
  3. Put in orderOperator Precedence - Hierarchy

Useful articles