Precedence¶
We all know that 2 + 3 * 7
is 23
and not 35
. The reason is that the *
operator has a higher precedence than the +
operator and is, therefore, evaluated first. These precedence rules are necessary for all types of expressions listed above and shown in the following list. The higher up an expression is in the list, the higher its precedence and the earlier it is evaluated. Expressions listed beside each other have the same precedence and are evaluated from left to right:
- HIGHER PRECEDENCE
()
(parentheses around an expression)1
(integer literals),1.0
(float literals),"a"
(string literals),true
/false
(boolean literals),null
(null literal),someName
(references),"age: {{ age }}"
(template strings)()
(calls),?()
(null-safe calls),.
(member accesses),?.
(null-safe member accesses),[]
(indexed accesses),?[]
(null-safe indexed accesses)-
(unary, arithmetic negations)as
(type casts)?:
(Elvis operators)*
,/
(multiplicative operators)+
,-
(binary, additive operators)<
,<=
,>=
,>
(comparison operators)===
,==
,!==
,!=
(equality operators)not
(logical negations)and
(conjunctions)or
(disjunctions)() -> 1
(expression lambdas),() {}
(block lambdas)- LOWER PRECEDENCE
If the default precedence of operators is not sufficient, parentheses can be used to force a part of an expression to be evaluated first.