JavaScript Operator Precedence
Understanding the order of operations in JavaScript
🎯 What is Operator Precedence?
Operator precedence determines the order in which operators are evaluated in expressions. Understanding precedence helps you write correct code and avoid unexpected results.
// Without parentheses - precedence matters!
let result = 2 + 3 * 4;
console.log(result); // 14 (not 20!)
// Multiplication happens first: 2 + (3 * 4) = 2 + 12 = 14
Output:
14
Precedence Levels (High to Low)
Highest
Grouping, Member access
() [] .
High
Unary, Exponentiation
! + - ++ -- **
Medium
Arithmetic, Comparison
* / % + - < > <= >=
Low
Logical, Assignment
&& || ? : =
🔹 Precedence Table
| Precedence | Operator | Description | Associativity |
|---|---|---|---|
| 20 |
( )
|
Grouping | n/a |
| 19 |
. []
|
Member access | left-to-right |
| 16 |
! + - ++ --
|
Unary | right-to-left |
| 15 |
**
|
Exponentiation | right-to-left |
| 14 |
* / %
|
Multiplication, Division | left-to-right |
| 13 |
+ -
|
Addition, Subtraction | left-to-right |
| 11 |
< <= > >=
|
Relational | left-to-right |
| 10 |
== != === !==
|
Equality | left-to-right |
| 6 |
&&
|
Logical AND | left-to-right |
| 5 |
||
|
Logical OR | left-to-right |
| 3 |
? :
|
Ternary | right-to-left |
| 2 |
= += -= *=
|
Assignment | right-to-left |
🔹 Precedence Examples
See how precedence affects expression evaluation:
// Arithmetic precedence
console.log(2 + 3 * 4); // 14 (not 20)
console.log((2 + 3) * 4); // 20 (parentheses override)
// Mixed operators
console.log(10 - 3 * 2); // 4 (10 - 6)
console.log(10 / 2 + 3); // 8 (5 + 3)
console.log(2 ** 3 * 4); // 32 (8 * 4)
// Comparison and logical
console.log(5 > 3 && 2 < 4); // true
console.log(5 > 3 || 2 > 4); // true
console.log(!false && true); // true
// Assignment precedence
let a, b, c;
a = b = c = 5; // Right-to-left: c=5, b=5, a=5
console.log(a, b, c); // 5 5 5
// Ternary precedence
let x = 10;
let result = x > 5 ? "big" : "small";
console.log(result); // "big"
Output:
14
20
4
8
32
true
true
true
5 5 5
big
20
4
8
32
true
true
true
5 5 5
big
🔹 Best Practices
Tips for writing clear code with proper precedence:
// ❌ Unclear without parentheses
let unclear = a && b || c && d;
// ✅ Clear with parentheses
let clear = (a && b) || (c && d);
// ❌ Complex expression
let complex = x + y * z / w - v;
// ✅ Broken down for clarity
let temp = y * z / w;
let simple = x + temp - v;
// ❌ Nested ternary
let nested = a ? b ? c : d : e;
// ✅ Clear if-else or separate ternary
let readable = a ? (b ? c : d) : e;
// Always use parentheses when in doubt!
let safe = (a + b) * (c - d);
console.log(safe);
Output:
(depends on variable values)