Precedence
Operator precedence defines which operations are performed first when multiple operators appear in an expression. Higher precedence operations are evaluated before lower precedence ones.
Precedence Table (highest to lowest)
Section titled “Precedence Table (highest to lowest)”| Precedence | Operators | Description |
|---|---|---|
| 1 | (), [], . | Primary expressions (literals, identifiers, function calls) |
| 2 | not, !, +, - | Unary operators |
| 3 | *, /, % | Multiplicative arithmetic |
| 4 | +, - | Additive arithmetic |
| 5 | <, <=, >, >=, in, matches, contains | Comparison operators |
| 6 | ==, !=, is, is not | Equality operators |
| 7 | and | Logical AND |
| 8 | xor | Logical XOR |
| 9 | or | Logical OR |
| 10 | ? : | Ternary conditional |
Examples
Section titled “Examples”Arithmetic Precedence
Section titled “Arithmetic Precedence”let result: number = 2 + 3 * 4 -- Result: 14 (not 20)let calculation: number = 10 / 2 + 3 -- Result: 8.0 (not 1.25)Comparison vs Arithmetic
Section titled “Comparison vs Arithmetic”let is_valid: bool = 5 + 3 > 7 -- Result: truelet check: bool = 10 * 2 == 20 -- Result: trueLogical Precedence
Section titled “Logical Precedence”let complex: bool = true and false or true -- Result: truelet mixed: bool = 5 > 3 and 2 < 4 -- Result: trueTernary Precedence
Section titled “Ternary Precedence”let value: number = 5 > 3 ? 10 : 20 -- Result: 10let nested: string = true ? (false ? "A" : "B") : "C" -- Result: "B"Using Parentheses
Section titled “Using Parentheses”Override Precedence
Section titled “Override Precedence”-- Without parentheses (follows precedence)let result1: number = 2 + 3 * 4 -- Result: 14
-- With parentheses (override precedence)let result2: number = (2 + 3) * 4 -- Result: 20Complex Expressions
Section titled “Complex Expressions”-- Clear grouping for readabilitylet access: bool = (user.age >= 18 and user.verified) or (user.role == "admin" and user.active)
-- Mixed operationslet calculation: number = (10 + 5) * (3 - 1) / 2 -- Result: 15.0
-- Same precedence is evaluated from left to rightlet calculation: number = (10 + 5) * (5 - 2) / 2 -- Result: 22.5 (15 * 3 / 2)Best Practices
Section titled “Best Practices”Use Parentheses for Clarity
Section titled “Use Parentheses for Clarity”-- Good: Clear intentlet result: bool = (a and b) or (c and d)
-- Avoid: Relying on precedence knowledgelet result: bool = a and b or c and dGroup Related Operations
Section titled “Group Related Operations”-- Good: Logical groupinglet price: number = (base_price + tax) * discount_rate
-- Good: Comparison groupinglet valid: bool = (age >= 18) and (income > 50000)Break Complex Expressions
Section titled “Break Complex Expressions”-- Good: Step-by-step calculationlet temp1: number = base_price + taxlet temp2: number = temp1 * discount_ratelet final_price: number = temp2 - shipping
-- Avoid: One complex expressionlet final_price: number = (base_price + tax) * discount_rate - shipping