The next class of operators for our discussion are called compound assignment operators: "+=", "-=", "*=", "/=", and "%=". These operators are used when we need to update the value of a variable. Thus, to increase var1 by 10, we could simply write "var1 += 10", instead of "var1 = var1 + 10". Similarly, to multiply var with 10, we could simply write "var1 *= 10", instead of "var1 = var1 * 10". Same rule applies to other operations.
The first example (provided below) demonstrates usage of basic arithmetic operations. This example computes sum and product of two variables.
Now, let us run this program (store it in a file, say "basic.html", and load it using a browser). As expected, the output prints the value of these two variables along with their sum and the product.
Note that the above program assigns values to various variables e.g "var1 = 100". An assignment operation takes the value on the right side (e.g. 100) and stores it in the variable (e.g. var1) on the left side. For such assignment operations, ordering is important. We must keep the variable (often referred to as lvalue) on the left and keep the values (literal or yet another variable holding a value) on the right. Assigning in the opposite manner ("100 = var1") would simply be an error!
The second examples shows the usage of compound and increment operators; for the sake of brevity, we show the output as comments after the respective operation.
As we can see, "++var1" increases the value of var1 first and then assigns it to var2; thus, var2 becomes 11. On the other hand, "var1++" assigns the value first to var3 and then increases the value of var1; thus, var3 becomes 10.
When there are several operations, it is possible that an expression containing more than two of these operations can appear ambiguous. As an example, for expression, "var1 = 10 * 2 + 7 ;", it is not clear if we first multiply 10 by 2 and then add 7 (so that var1 becomes 27) or first add 2 to 7 and then multiply with 10 (so that var1 becomes 90).
|++, --||Increment and decrement|
|*, /, %||Multiplication, division, and modulo|
|+, -||Addition and subtraction|
|+=, -=, *=, /=, .=, %=||Compound assignments|
In the above list, parentheses has a higher precedence than other operators and hence, where ever there is less clarity, we can simply use parentheses to avoid ambiguity. Using parentheses also improves readability of the code. Thus, in our earlier program, if we wish to do addition first, followed by multiplication, then we can clearly specify it as "var1 = 10 * (2 + 7);". Else, if we intend to multiply 10 and 2 first and then add 7 to the result, then we can clearly specify it as "var1 = (10 * 2) + 7;". It is a good programming practice to use parentheses richly and thereby, avoid ambiguities.