Priority and associativity determine how and in what order the term should be divided into sub-terms. In other words, it defines rules in which brackets must be set implicitly unless explicitly specified.
If you have a term without parentheses, you start with the operators with the lowest precedence and enclose them in parentheses.
For instance:
Precendences:
Term:
!person.isMarried && person.age == 25 + 2 * 5
will be grouped as follows:
- ! (person.isMarried) && & (person.age) == 25 + 2 * 5
- (! (person.isMarried)) && & (person.age) == 25 + 2 * 5
- (! (person.isMarried)) && & (person.age) == 25 + (2 * 5)
- (! (person.isMarried)) && & (person.age) == (25 + (2 * 5))
- (! (person.isMarried)) && & ((person.age) == (25 + (2 * 5)))
- ((! (person.isMarried)) && ((person.age) == (25 + (2 * 5))))
One very common rule is the priority * and / before + and -.
Associativity determines in which direction operators with the same priority are grouped. Most operators are from left to right. Unary prefix operators from right to left.
Example:
1 + 2 + 3 + 4
grouped as follows:
- (1 + 2) + 3 + 4
- ((1 + 2) + 3) + 4
- (((1 + 2) + 3) + 4)
a
!! + 1
grouped as
- !! (+ 1)
- ! (! (+ 1))
- (! (! (+ 1)))
Does everything still comply with the BODMAS / PEDMAS rules you encountered?
source share