Course contentsShow
← JavaScript
Lesson 272 of 2,7237. Arithmetic and OperatorsFree lesson

Common Precedence Pitfalls

Real-world mistakes like `a && b == c` or `x + y + ''`, and how precedence causes unexpected behavior.

Common Precedence Pitfalls

What you'll learn: The real-world mistakes that even experienced developers make when operator precedence doesn't work the way they expect.

The Problem with Mixing Operators

You've learned the rules of precedence, but certain combinations of operators create tricky situations where your code looks right but behaves unexpectedly. These pitfalls happen because our mental model of "what should happen" conflicts with JavaScript's precedence rules.

Classic Pitfall #1: Logical AND with Comparison

let a = true;
let b = 5;
let c = 10;

// What you might think this means:
// "Is a true AND does b equal c?"
let result = a && b == c;  // false

// What JavaScript actually evaluates:
// (a && b) == c
// (true && 5) == 10
// 5 == 10
// false

The && operator has higher precedence than ==, so it evaluates first, returning 5. Then 5 == 10 is false. You probably wanted a && (b == c).

Classic Pitfall #2: String Coercion in Math

let x = 5;
let y = 10;

let result = x + y + '';  // "15" ✓
let result2 = '' + x + y; // "510" ✗

The + operator is left-associative. In the first case: (5 + 10) + '' becomes 15 + '' = "15". In the second: ('' + 5) + 10 becomes "5" + 10 = "510" because string concatenation takes over.

Classic Pitfall #3: Assignment in Conditions

let isValid = false;

if (isValid = true) {  // Assignment, not comparison!
    // Always executes
}

Assignment has very low precedence but still evaluates. The assignment returns true, making the condition always pass.

Key Takeaway: When mixing operators—especially logical operators with comparisons, or addition with strings—use parentheses liberally to make your intent crystal clear, even if technically "not needed."