The precedence of the operators determines which operators are evaluated before others in complex expressions where several operators are involved.
For operators on the same level of precedence, both JavaScript and JScript .NET reads and evaluates expressions from left to right. The table below lists the order of precedence for the operators, from highest to lowest.
Operator |
|
1 |
() |
2 |
!, -- , ++, -, new |
3 |
*, /, % |
4 |
+, - |
5 |
<, <=, >, >= |
6 |
==, !=, ===, !== |
7 |
&& |
8 |
|| |
9 |
?: |
10 |
=, +=, -=, *=, /=, %= |
The minus (-) in 2 is the unary negation operator, not subtraction.
Note that parentheses are at the top of the table, so by using parentheses you can always control in what order the expressions are calculated. It is highly recommended to use parentheses, also because it makes the expressions easier to understand.
Here is an example showing how the order of precedence decides how an expression is calculated:
3 + 4 * 2
|
3 + 8
|
11
This is a piece of code from a script. For each one of these assignments, find the value of x, y and z after the line has been executed:
x = 4; y=0; z=0;
y = 5*2+1-(x++ == 4 ? 2 : 8) //ex. a
z = ((x+4)%3)*900+8 //ex. b
y+= --x*8-(z>3 ? z : ++z) //ex. c
x = (z == 8 && (z % 3 == 0) || ++y < 6*5) ? --z : ++y //ex. d
See the answers in APPENDIX A Answers to Exercises.