Operator precedence
When an expression makes use of more than one operator, Carrot relies on a set of rules to determine the order in which each operator is evaluated. Carrot follows a standard order of operations when evaluating an expression based on operator precedence. Operators that have a higher precedence in the table below will be evaluated first.
Precedence | Operator | Associativity |
9 | [ ](array) . (dot) | left to right |
8 | ! (not) | right to left |
7 | * (multiply) / (divide) % (modulus) | left to right |
6 | + (add) - (subtract) | left to right |
5 | < (less-than) <= (less-than-equals) > (greater-than) >= (greater-than-equals) | not associative |
4 | : (match) = (equals) != (not-equals) | left to right |
3 | && (and) | left to right |
2 | || (or) | left to right |
1 | ? (ternary) ?: (elvis) | right to left |
Consider the expression below.
Without operator precedence, Carrot would not know which operation to complete first. If we refer to the table above, we see that multiplication has a higher precedence than addition. Thus, variableA * variableB is evaluated first, then the result of that expression is added to variableC.
Of course, addition and multiplication are two well known examples of operator precedence in arithmetic, and it works in the same way in Carrot. Just like arithmetic, if you wanted to change the precedence of the above expression, you would use parenthesis as illustrated below.
In the above expression, we are telling Carrot to explicitly add variableB to variableC before multiplying the result by variableA.