Operator precedence determines the way in which operators are parsed with respect to each other.
Operators with higher precedence become the operands of operators with lower precedence.
In the following example, multiplication has a higher precedence than addition, which determines the outcome of the equation.
// First multiply 3 by 5, then add 10
var x = 10 + 3 * 5;
If instead we would like to run the addition operation first, we should group it in parentheses, which always has the highest precedence.
// First add 10 and 3, then multiply by 5
var x = (10 + 3) * 5;
When using parentheses, the operations inside the parentheses are computed first.
When many operations have the same precedence (like addition and subtraction), they are computed from left to right:
var x = 10 + 3 - 5;
Expression evaluation is also influenced by the operator associativity.
Associativity means the direction (right to left or left to right) in which entire expression is evaluated.
If two or more operators with the same level of precedence appear in an expression, which will be evaluated first? The operator associativity answers this question.
|Operator||Operator Use||Operator Associativity||Operator Precedence|
|()||Method/function call, grouping||Left to right||Highest — 1|
|||Array access||Left to right||1|
|.||Object property access||Left to right||1|
|++||Increment||Right to left||2|
|--||Decrement||Right to left||2|
|-||Negation||Right to left||2|
|!||Logical NOT||Right to left||2|
|~||Bitwise NOT||Right to left||2|
|delete||Removes array value or object property||Right to left||2|
|new||Creates an object||Right to left||2|
|typeof||Returns data type||Right to left||2|
|void||Specifies no value to return||Right to left||2|
|/||Division||Left to right||3|
|*||Multiplication||Left to right||3|
|%||Modulus||Left to right||3|
|+||Plus||Left to right||4|
|+||String Concatenation||Left to right||4|
|-||Subtraction||Left to right||4|
|>>||Bitwise right-shift||Left to right||5|
|<<||Bitwise left-shift||Left to right||5|
|>, >=||Greater than, greater than or equal to||Left to right||6|
|<, <=||Less than, less than or equal to||Left to right||6|
|==||Equality||Left to right||7|
|!=||Inequality||Left to right||7|
|===||Identity operator — equal to (and same data type)||Left to right||7|
|!==||Non-identity operator — not equal to (or don't have the same data type)||Left to right||7|
|&||Bitwise AND||Left to right||8|
|^||Bitwise XOR||Left to right||9|
||||Bitwise OR||Left to right||10|
|&&||Logical AND||Left to right||11|
|||||Logical OR||Left to right||12|
|?:||Conditional branch||Left to right||13|
|=||Assignment||Right to left||14|
|*=, /=, %=, +=,, -=, <<=, >>=, >>>=, &=, ^=, |=||Assignment according to the preceding operator||Right to left||14|
|,||Multiple evaluation||Left to right||Lowest: 15|