0
0
Javascriptprogramming~15 mins

Operator precedence in Javascript - Deep Dive

Choose your learning style9 modes available
Overview - Operator precedence
What is it?
Operator precedence is the set of rules that decides the order in which parts of a math or logic expression are calculated. When you write an expression with many operators, like +, -, *, or /, the computer uses precedence to know which part to do first. Without these rules, the computer wouldn't know how to solve expressions correctly. This helps make sure your code works as you expect.
Why it matters
Without operator precedence, computers would have to guess the order of operations, leading to wrong answers and confusing bugs. Imagine if 2 + 3 * 4 was always calculated left to right, giving 20 instead of 14. Operator precedence makes math and logic in code reliable and predictable, so programs behave correctly and safely.
Where it fits
Before learning operator precedence, you should understand basic operators like addition, multiplication, and logical operators. After mastering precedence, you can learn about associativity, parentheses usage, and how to write complex expressions clearly and safely.
Mental Model
Core Idea
Operator precedence is the rulebook that tells the computer which parts of an expression to calculate first when multiple operators appear together.
Think of it like...
It's like following traffic lights at an intersection: some roads have green lights first, so cars go before others. Operator precedence decides which 'cars' (operations) move first to avoid crashes (wrong results).
Expression: 2 + 3 * 4

Precedence order:
  ┌───────────────┐
  │ Multiply (*)  │
  └──────┬────────┘
         │
  ┌──────▼────────┐
  │ Add (+)       │
  └───────────────┘

Calculation steps:
  3 * 4 = 12
  2 + 12 = 14
Build-Up - 7 Steps
1
FoundationUnderstanding basic operators
🤔
Concept: Learn what operators like +, -, *, and / do in JavaScript.
Operators are symbols that perform actions on values. For example, + adds numbers, - subtracts, * multiplies, and / divides. Each operator takes one or two values (called operands) and produces a result.
Result
You can write simple expressions like 5 + 3 or 10 / 2 and get correct answers.
Knowing what each operator does is the first step before understanding how they combine in expressions.
2
FoundationEvaluating simple expressions
🤔
Concept: Learn how JavaScript calculates expressions with one operator.
When you write 4 + 7, JavaScript adds 4 and 7 to get 11. For 8 * 3, it multiplies 8 by 3 to get 24. These are straightforward because only one operator is involved.
Result
Expressions with one operator produce expected results immediately.
Simple expressions build the base for understanding how multiple operators interact.
3
IntermediateIntroducing operator precedence rules
🤔Before reading on: do you think 2 + 3 * 4 equals 20 or 14? Commit to your answer.
Concept: Operator precedence defines which operator runs first when multiple appear in an expression.
In JavaScript, multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-). So in 2 + 3 * 4, JavaScript first calculates 3 * 4 = 12, then adds 2 + 12 = 14.
Result
The expression 2 + 3 * 4 evaluates to 14, not 20.
Understanding precedence prevents mistakes in how expressions are evaluated and helps predict results.
4
IntermediateUsing parentheses to override precedence
🤔Before reading on: what does (2 + 3) * 4 evaluate to? Predict the result.
Concept: Parentheses change the normal precedence by forcing parts of the expression to calculate first.
When you write (2 + 3) * 4, JavaScript calculates inside the parentheses first: 2 + 3 = 5, then multiplies 5 * 4 = 20. Parentheses have the highest precedence.
Result
The expression (2 + 3) * 4 evaluates to 20.
Knowing how parentheses affect precedence lets you control calculation order explicitly.
5
IntermediatePrecedence with logical operators
🤔Before reading on: does && (AND) have higher precedence than || (OR)? Guess yes or no.
Concept: Operator precedence also applies to logical operators like AND (&&) and OR (||).
In JavaScript, && has higher precedence than ||. So in true || false && false, JavaScript first evaluates false && false = false, then true || false = true.
Result
The expression true || false && false evaluates to true.
Understanding precedence in logic helps avoid bugs in conditions and control flow.
6
AdvancedOperator associativity explained
🤔Before reading on: does 10 - 5 - 2 evaluate as (10 - 5) - 2 or 10 - (5 - 2)? Choose one.
Concept: Associativity defines the order operators of the same precedence are evaluated (left to right or right to left).
Most operators like + and - are left-associative, so 10 - 5 - 2 is (10 - 5) - 2 = 3. Some operators like assignment (=) are right-associative, so a = b = 5 assigns 5 to b, then to a.
Result
10 - 5 - 2 evaluates to 3 because subtraction is left-associative.
Knowing associativity clarifies how expressions with repeated operators are grouped and evaluated.
7
ExpertSurprises with unary and ternary operators
🤔Before reading on: does the unary minus (-) have higher precedence than multiplication (*)? Guess yes or no.
Concept: Unary operators like - (negation) and the ternary operator (?:) have their own precedence rules that can affect expressions unexpectedly.
Unary minus (-) has higher precedence than multiplication, so -2 * 3 is (-2) * 3 = -6. The ternary operator ?: has lower precedence than most operators, so expressions with ?: often need parentheses to avoid confusion.
Result
-2 * 3 evaluates to -6; a ? b : c + d evaluates as a ? b : (c + d).
Understanding these special cases prevents subtle bugs and clarifies complex expressions.
Under the Hood
JavaScript uses a fixed table of operator precedence values internally. When parsing an expression, it compares operator precedence to decide which operations to perform first. The parser builds an abstract syntax tree (AST) where nodes with higher precedence operators are deeper, ensuring correct evaluation order.
Why designed this way?
This design follows mathematical conventions and logical reasoning to make code intuitive and predictable. Alternatives like always left-to-right evaluation would break common math rules and confuse developers. The precedence table balances simplicity and expressiveness.
Expression parsing flow:

Input: 2 + 3 * 4

┌───────────────┐
│ Tokenize input│
└──────┬────────┘
       │
┌──────▼────────┐
│ Build AST     │
│ * has higher  │
│ precedence    │
└──────┬────────┘
       │
┌──────▼────────┐
│ Evaluate AST  │
│ 3 * 4 = 12   │
│ 2 + 12 = 14  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does 2 + 3 * 4 equal 20 because addition comes first? Commit yes or no.
Common Belief:People often think operators are evaluated strictly left to right, so 2 + 3 * 4 equals 20.
Tap to reveal reality
Reality:Multiplication has higher precedence than addition, so 3 * 4 is done first, making the result 14.
Why it matters:Ignoring precedence leads to wrong calculations and bugs that are hard to spot.
Quick: Does adding parentheses always change the result? Commit yes or no.
Common Belief:Some believe parentheses are just for readability and don't affect calculation order.
Tap to reveal reality
Reality:Parentheses have the highest precedence and always change the order of evaluation, potentially changing results.
Why it matters:Misusing parentheses can cause unexpected results or logic errors.
Quick: Is the ternary operator ?: evaluated before multiplication? Guess yes or no.
Common Belief:Many think the ternary operator has high precedence and runs before arithmetic operators.
Tap to reveal reality
Reality:The ternary operator has lower precedence than most arithmetic operators, so arithmetic runs first unless parentheses are used.
Why it matters:Misunderstanding this causes confusing bugs in conditional expressions.
Quick: Does associativity mean operators always group left to right? Commit yes or no.
Common Belief:People often assume all operators associate left to right.
Tap to reveal reality
Reality:Some operators, like assignment (=), associate right to left, changing evaluation order.
Why it matters:Wrong assumptions about associativity can cause unexpected variable values and logic errors.
Expert Zone
1
Unary operators like ++ and -- have higher precedence than most binary operators, affecting how expressions are parsed.
2
The comma operator has very low precedence but can change expression results by evaluating multiple expressions in sequence.
3
Short-circuit logical operators (&&, ||) not only have precedence but also control flow effects that affect evaluation order and side effects.
When NOT to use
Operator precedence rules are fixed in JavaScript and cannot be changed. When expressions become too complex or unclear, it's better to use parentheses or split calculations into multiple statements for clarity and maintainability.
Production Patterns
In real-world code, developers rely on operator precedence to write concise expressions but use parentheses generously to avoid ambiguity. Linters and code reviews often enforce clear precedence usage to prevent bugs. Complex expressions are often broken down for readability and debugging.
Connections
Mathematics order of operations
Operator precedence in programming directly builds on the mathematical order of operations (PEMDAS/BODMAS).
Understanding math order of operations helps grasp programming precedence rules quickly since they follow similar logic.
Parsing and compiler design
Operator precedence is a key part of how parsers build syntax trees from code.
Knowing precedence helps understand how compilers and interpreters read and execute code correctly.
Human decision-making priorities
Operator precedence mirrors how humans prioritize tasks or decisions based on importance or urgency.
Recognizing this connection shows how programming mimics natural prioritization to manage complexity.
Common Pitfalls
#1Ignoring operator precedence and expecting left-to-right evaluation.
Wrong approach:let result = 2 + 3 * 4; // expecting 20
Correct approach:let result = 2 + 3 * 4; // actually 14 because * has higher precedence
Root cause:Misunderstanding that multiplication runs before addition regardless of position.
#2Not using parentheses to clarify complex expressions.
Wrong approach:let value = a || b && c; // unclear order
Correct approach:let value = a || (b && c); // explicit grouping
Root cause:Assuming logical operators have equal precedence or that code reads left to right.
#3Misusing the ternary operator without parentheses.
Wrong approach:let x = a ? b : c + d; // expecting c to be chosen alone
Correct approach:let x = a ? b : (c + d); // correct grouping
Root cause:Not knowing ternary has lower precedence than addition.
Key Takeaways
Operator precedence defines the order in which parts of an expression are calculated, ensuring correct results.
Multiplication and division have higher precedence than addition and subtraction in JavaScript.
Parentheses override normal precedence and should be used to clarify complex expressions.
Associativity determines how operators of the same precedence group, usually left to right but sometimes right to left.
Understanding precedence and associativity helps prevent bugs and write clearer, more predictable code.