JavaScript Operator Precedence: Complete Guide with Examples
Learn how JavaScript operator precedence determines the order of operations in expressions. Master grouping, associativity, and evaluation rules with practical code examples.
JavaScript operator precedence determines which parts of an expression get evaluated first when multiple operators appear in the same statement. If you have ever written a calculation that returned an unexpected result, the answer almost always traces back to precedence rules.
Think of operator precedence like the order of operations you learned in math class. Multiplication happens before addition, parentheses override everything, and there is a specific pecking order that the JavaScript engine follows every single time. Understanding this pecking order is the difference between expressions that work correctly and subtle bugs that take hours to track down.
This guide walks you through every precedence level that matters in daily JavaScript development, with real code examples that demonstrate exactly how the engine evaluates each expression.
What is Operator Precedence in JavaScript?
Operator precedence is a set of rules that the JavaScript engine uses to decide which operator in an expression executes first. When an expression contains multiple operators, the engine does not simply read left to right. Instead, it consults a precedence table and evaluates higher-precedence operators before lower-precedence ones.
// Without knowing precedence, what does this return?
const result = 2 + 3 * 4;
console.log(result); // 14, not 20
// The engine evaluates 3 * 4 first (precedence 13)
// Then evaluates 2 + 12 (precedence 12)The ECMAScript specification defines 19 precedence levels, numbered from 1 (lowest) to 19 (highest). Operators with higher precedence numbers execute before operators with lower numbers.
Why Precedence Matters for Real Code
Precedence is not just an academic concept. It directly affects real code decisions:
// Bug: developer intended to check if user is active AND has admin role
const hasAccess = isActive || isAdmin && hasPermission;
// Actually evaluates as: isActive || (isAdmin && hasPermission)
// Because && has higher precedence than ||
// Fix: use explicit parentheses
const hasAccess = (isActive || isAdmin) && hasPermission;The JavaScript Operator Precedence Table
Here is a practical reference table covering the operators you will encounter most frequently. Higher numbers mean the operator executes first.
| Precedence | Operator | Description | Associativity |
|---|---|---|---|
| 19 | () | Grouping (parentheses) | N/A |
| 18 | . [] () ?. | Member access, computed access, function call, optional chaining | Left-to-right |
| 17 | new (with args) | Constructor call | N/A |
| 16 | ++ -- (postfix) | Postfix increment/decrement | N/A |
| 15 | ! ~ typeof void delete ++ -- (prefix) | Unary operators | Right-to-left |
| 14 | ** | Exponentiation | Right-to-left |
| 13 | * / % | Multiplication, division, remainder | Left-to-right |
| 12 | + - | Addition, subtraction | Left-to-right |
| 11 | << >> >>> | Bitwise shift | Left-to-right |
| 10 | < <= > >= in instanceof | Relational | Left-to-right |
| 9 | == != === !== | Equality | Left-to-right |
| 8 | & | Bitwise AND | Left-to-right |
| 7 | ^ | Bitwise XOR | Left-to-right |
| 6 | | | Bitwise OR | Left-to-right |
| 5 | && | Logical AND | Left-to-right |
| 4 | || ?? | Logical OR, Nullish coalescing | Left-to-right |
| 3 | ? : | Ternary conditional | Right-to-left |
| 2 | = += -= *= etc. | Assignment | Right-to-left |
| 1 | , | Comma | Left-to-right |
Understanding Associativity
When two operators share the same precedence level, associativity determines the evaluation direction. Left-to-right associativity means the leftmost operator executes first. Right-to-left means the rightmost goes first.
// Left-to-right associativity (subtraction, precedence 12)
const result = 10 - 5 - 2;
// Evaluates as: (10 - 5) - 2 = 3
// NOT as: 10 - (5 - 2) = 7
console.log(result); // 3// Right-to-left associativity (assignment, precedence 2)
let a, b, c;
a = b = c = 10;
// Evaluates as: a = (b = (c = 10))
// c gets 10, then b gets 10, then a gets 10
console.log(a, b, c); // 10 10 10Exponentiation is Right-to-Left
The exponentiation operator (**) is one of the few arithmetic operators with right-to-left associativity:
const result = 2 ** 3 ** 2;
// Evaluates as: 2 ** (3 ** 2) = 2 ** 9 = 512
// NOT as: (2 ** 3) ** 2 = 8 ** 2 = 64
console.log(result); // 512Grouping with Parentheses (Precedence 19)
Parentheses have the highest precedence level in JavaScript. They override every other precedence rule, making them your most reliable tool for controlling evaluation order.
// Without parentheses
const price = 100 + 50 * 0.1;
console.log(price); // 105 (50 * 0.1 happens first)
// With parentheses to calculate total first
const discountedPrice = (100 + 50) * 0.1;
console.log(discountedPrice); // 15 (100 + 50 happens first)When in Doubt, Use Parentheses
Even when you know the precedence rules, adding parentheses makes your intent explicit to other developers reading your code. Readable code is more valuable than clever code. A team member who has to look up the precedence table to understand your expression is a team member who might introduce a bug during a quick edit.
Nested Parentheses
Nested parentheses evaluate from the innermost group outward:
const result = ((2 + 3) * (4 - 1)) / 5;
// Step 1: (2 + 3) = 5
// Step 2: (4 - 1) = 3
// Step 3: 5 * 3 = 15
// Step 4: 15 / 5 = 3
console.log(result); // 3Arithmetic Operator Precedence in Practice
Arithmetic operators follow the same PEMDAS/BODMAS rules you know from mathematics, but JavaScript adds a few extras.
| Operation | Operator | Precedence | Example | Result |
|---|---|---|---|---|
| Exponentiation | ** | 14 | 2 ** 3 | 8 |
| Multiplication | * | 13 | 4 * 3 | 12 |
| Division | / | 13 | 10 / 2 | 5 |
| Remainder | % | 13 | 10 % 3 | 1 |
| Addition | + | 12 | 5 + 3 | 8 |
| Subtraction | - | 12 | 9 - 4 | 5 |
// Real-world example: calculating a shopping cart total with tax and discount
const subtotal = 3 * 29.99 + 2 * 14.99;
// Evaluates as: (3 * 29.99) + (2 * 14.99)
// = 89.97 + 29.98 = 119.95
const taxRate = 0.08;
const discount = 10;
// Parentheses needed here to get the right calculation
const total = (subtotal - discount) * (1 + taxRate);
console.log(total.toFixed(2)); // "118.75"Logical Operator Precedence
Logical operators have a specific order that catches many developers off guard: ! (NOT) executes first, then && (AND), then || (OR).
// Logical NOT has highest precedence among logical operators
const a = !true || false;
// Evaluates as: (!true) || false = false || false = false
// AND before OR
const b = true || false && false;
// Evaluates as: true || (false && false) = true || false = true
// Common access control pattern
const isAdmin = false;
const isOwner = true;
const isPublished = false;
// Without understanding precedence, this is confusing
const canEdit = isAdmin || isOwner && isPublished;
// Evaluates as: isAdmin || (isOwner && isPublished)
// = false || (true && false) = false || false = false
// What the developer probably wanted
const canEditFixed = (isAdmin || isOwner) && isPublished;
// = (false || true) && false = true && false = false
// OR maybe this
const canEditAlt = isAdmin || (isOwner && isPublished);
// = false || (true && false) = falseCommon Pitfall with Mixed Logical Operators
When mixing && and || in the same expression, always use parentheses to make your intent clear. The precedence rules are well-defined, but your teammates (and your future self reviewing the code at 2 AM during an incident) will thank you for the explicit grouping.
Comparison and Equality Operators
Comparison operators (<, >, <=, >=) have higher precedence than equality operators (==, ===, !=, !==), and both sit above logical operators:
// Comparison (10) before equality (9) before logical AND (5)
const result = 5 > 3 === true && 10 < 20;
// Step 1: 5 > 3 → true (comparison, precedence 10)
// Step 2: 10 < 20 → true (comparison, precedence 10)
// Step 3: true === true → true (equality, precedence 9)
// Step 4: true && true → true (logical AND, precedence 5)
console.log(result); // true// Practical example: form validation
const age = 25;
const hasConsent = true;
const country = "US";
const isEligible = age >= 18 && age <= 65 && hasConsent === true;
// All comparisons evaluate first, then && chains them
// (age >= 18) && (age <= 65) && (hasConsent === true)
// true && true && true = true
console.log(isEligible); // trueAssignment Operator Precedence
Assignment operators have one of the lowest precedence levels (2), which means nearly everything else evaluates before the value is assigned to the variable.
// Assignment happens last
let x = 2 + 3 * 4;
// Step 1: 3 * 4 = 12 (multiplication, precedence 13)
// Step 2: 2 + 12 = 14 (addition, precedence 12)
// Step 3: x = 14 (assignment, precedence 2)
console.log(x); // 14Compound Assignment Operators
Compound assignment operators (+=, -=, *=, etc.) also have precedence 2 and right-to-left associativity:
let score = 100;
score += 5 * 2;
// Step 1: 5 * 2 = 10 (multiplication first)
// Step 2: score = score + 10 = 110 (compound assignment)
console.log(score); // 110The Ternary Operator and Precedence
The ternary (conditional) operator sits at precedence 3, just above assignment. This means comparisons and logical operators evaluate before the ternary decides which branch to take:
// Comparison evaluates before ternary
const age = 20;
const category = age >= 18 ? "adult" : "minor";
// Step 1: age >= 18 → true (comparison, precedence 10)
// Step 2: true ? "adult" : "minor" → "adult" (ternary, precedence 3)
console.log(category); // "adult"// Nested ternary with right-to-left associativity
const score = 85;
const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
// Evaluates right-to-left:
// score >= 90 ? "A" : (score >= 80 ? "B" : (score >= 70 ? "C" : "F"))
console.log(grade); // "B"The typeof Operator and Unary Precedence
The typeof operator sits at precedence 15 (unary), which is higher than all arithmetic and logical operators:
// typeof evaluates before comparison
const check = typeof 42 === "number";
// Step 1: typeof 42 → "number" (unary, precedence 15)
// Step 2: "number" === "number" → true (equality, precedence 9)
console.log(check); // true// typeof with arithmetic
const result = typeof 2 + 2;
// Step 1: typeof 2 → "number" (precedence 15)
// Step 2: "number" + 2 → "number2" (string concatenation, precedence 12)
console.log(result); // "number2"
// To check the type of the expression result, use parentheses
const corrected = typeof (2 + 2);
console.log(corrected); // "number"Best Practices
Writing Clear Expressions
Following these practices will save you from precedence-related bugs and make your code maintainable across teams.
Use parentheses for complex expressions. Even if you know that && binds tighter than ||, adding parentheses costs nothing and eliminates ambiguity. Code that requires a precedence table lookup to understand is code that will eventually contain a bug.
Break complex expressions into named variables. Instead of writing one massive expression with six operators, split it into intermediate variables with descriptive names. This makes the evaluation order explicit and the code self-documenting.
// Hard to read, requires precedence knowledge
const eligible = age >= 18 && income > 50000 || hasGuarantor && creditScore > 700;
// Clear, self-documenting
const meetsAgeAndIncome = age >= 18 && income > 50000;
const hasStrongGuarantor = hasGuarantor && creditScore > 700;
const eligible = meetsAgeAndIncome || hasStrongGuarantor;Never rely on precedence for side effects. If your expression depends on a specific evaluation order for side effects (like function calls or increments), restructure it into separate statements. Side effects combined with precedence create the kind of bugs that pass code review and break in production.
Learn the top 5 levels by heart. You do not need to memorize all 19 levels. Knowing that unary > arithmetic > comparison > logical > assignment covers 95% of real code situations.
Use strict equality (===) over loose equality (==). Both have the same precedence, but strict equality avoids implicit type conversion issues that interact poorly with other operators in complex expressions.
Common Mistakes and How to Avoid Them
Watch Out for These Pitfalls
These mistakes appear frequently in real codebases and can be difficult to catch during code review because the code looks syntactically correct.
Mixing && and || without parentheses. This is the most common precedence bug. Developers write a || b && c expecting left-to-right evaluation, but && always executes before ||. Always parenthesize mixed logical expressions.
Forgetting that + is both addition and concatenation. When mixing numbers and strings, the + operator can behave unexpectedly because string concatenation and numeric addition share the same precedence level:
const result = "Total: " + 10 + 5;
console.log(result); // "Total: 105" (string concatenation, left to right)
const corrected = "Total: " + (10 + 5);
console.log(corrected); // "Total: 15"Assuming assignment returns nothing. Assignment operators return the assigned value, which can create unexpected behavior when used inside conditions:
// Bug: assignment instead of comparison
let x = 0;
if (x = 5) {
console.log("This always runs because x = 5 returns 5, which is truthy");
}
// Fix: use comparison
if (x === 5) {
console.log("Correct comparison");
}Chaining comparisons like math notation. In math, 1 < x < 10 checks if x is between 1 and 10. In JavaScript, it does something completely different:
const x = 15;
const result = 1 < x < 10;
// Step 1: 1 < 15 → true (comparison, left to right)
// Step 2: true < 10 → true (true coerces to 1, and 1 < 10 is true)
console.log(result); // true (wrong! 15 is not less than 10)
// Correct way
const correct = x > 1 && x < 10;
console.log(correct); // falseUsing typeof with expressions without parentheses. When you want to check the type of an expression result, always wrap the expression in parentheses because typeof has very high precedence: typeof (a + b) not typeof a + b.
Next Steps
Practice with interactive exercises
Open your browser DevTools console and type out the expressions from this guide. Predict the result before pressing Enter, then verify. Pay special attention to mixed arithmetic and logical expressions.
Review your existing code for precedence issues
Search your codebase for expressions that mix && and || without parentheses. Add explicit grouping wherever the intent is not immediately obvious.
Learn JavaScript conditional statements
Operator precedence directly affects how conditions evaluate. Study how conditional statements use these operators to control program flow.
Explore type checking operators
Operators like typeof and instanceof have specific precedence levels that affect how they combine with other operators in expressions.
Rune AI
Key Insights
- Precedence levels: JavaScript has 19 levels; higher numbers execute first, with parentheses at the top (19) and comma at the bottom (1)
- Associativity: determines direction when operators share a level; most are left-to-right, but assignment and exponentiation are right-to-left
- Parentheses first: always use parentheses in mixed logical expressions (
&&with||) to prevent subtle bugs - Readability over cleverness: break complex expressions into named variables instead of relying on precedence knowledge
- Common trap:
&&binds tighter than||, soa || b && cevaluates asa || (b && c), not(a || b) && c
Frequently Asked Questions
What is operator precedence in JavaScript?
Do parentheses override operator precedence?
What is associativity in JavaScript operators?
Why does `&&` have higher precedence than `||`?
Should I memorize the entire precedence table?
How does operator precedence affect performance?
Conclusion
JavaScript operator precedence is a foundational concept that determines how every expression in your code gets evaluated. By understanding the core precedence levels and using parentheses strategically, you can write expressions that behave exactly as intended and remain readable to every developer on your team. The most practical approach is to memorize the five key precedence tiers (unary, arithmetic, comparison, logical, assignment) and use explicit grouping for everything else.
Tags
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.