Operator precedence refers to the priority given to operators while parsing a statement that has more than one operator performing operations in it. It is important to ensure the correct result and also to help the compiler understand what the order of operations should be. Operators with higher priorities are resolved first. But as one goes down the list, the priority decreases and hence their resolution.
Precedence and Associativity: Associativity in general states that irrespective of the order of operands for a given operation the result remains the same. Precedence is used to tell the compiler what operations should be performed first. For example, consider three numbers 2, 3, and 4. Now consider two operations:
( 2 + 3 ) + 4 = 2 + ( 3 + 4 ) ( 2 >= 3 ) or ( 1 != 4 )
The first operation is associativity where the order does not matter. The second case is precedence, where in order to reach the desired result there has to be a proper order in which operations will be performed.
Associativity is not a singular concept while dealing with precedence operations has to be dealt either with left-to-right or right-to-left associativity. This completely depends on the operation and tells the parser from which direction the operation should start.
// left-to-right associativity : division 3/4
// right-to-left associativity : assignment a = 3
Operator Precedence Table: The operator precedence table can help one know the precedence of an operator relative to other operators. As one goes down the table, the precedence of these operators decreases over each other, that is, the priority of an operator is lower than the operators above it and higher than the ones below it. The operators in the same row have the same priority.
In this table, 1 is the highest precedence and 19 is the lowest precedence.
|2||.||Member||left to right||obj.function|
|||Member||left to right||obj[“func”]|
|()||Function call||left to right||func()|
|4||++||Prefix increment||right to left||++i|
|5||**||Exponentiation||right to left||4**2|
|6||*||Multiplication||left to right||2*3|
|7||+||Addition||left to right||2+4|
|8||<<||Left shift||left to right||y<<2|
|>>>||Unsigned Right shift||y>>>2|
|9||<||Less than||left to right||3<4|
|<=||Less than or equal||3<=4|
|>=||Greater than or equal||4>=3|
|in||In||“PI” in MATH|
|instanceof||Instance of||A instanceof B|
|10||==||Equality||left to right||x==y|
|11||&||Bitwise AND||left to right||x&y|
|12||^||Bitwise XOR||left to right||x^y|
|13|||||Bitwise OR||left to right||x|y|
|14||&&||Logical AND||left to right||x&&y|
|15||||||Logical OR||left to right||x||y|
|16||? :||Conditional||right to left||(x>y)?x:y|
|17||Assignment||right to left||x=5|
|18||yield||Pause function||right to left||yield x|
|19||,||Comma||left to right||x,y|