November 22, 1999 - Avoiding Side Effects
November 22, 1999|
Avoiding Side Effects
Tips: November 1999
Yehuda Shiran, Ph.D.
number = 3; answer = ++number;
The first line is a simple assignment statement. The second line is a bit more complicated. It performs two actions in the following order:
number (side effect)
number (4) to
answer (main operation)
You could avoid the side effects in the second line above and use two different statements instead:
number = 3; number++; answer = number;
This set of statements is easy to follow. The advantage of the first method is that the code is compact and may run faster. The advantage of the second method is that the code is much more clearer and easier to understand and maintain. When the code is relatively short, I would go with the longer, simpler version.
document.write(myName = "Yehuda");
This statement prints
Yehuda. The assignment operation also takes place in this statement, so
myName holds the value
Yehuda after the statement. The assignment operation is the side effect, and the printing action is the main action. The preceding statement should be split into two separate statements:
myName = "Yehuda"; document.write(myName);
See if you can figure out the result this code:
number = 0; answer = (number++ - 2) * (--number - 1); document.write(number = answer++);
The rules of the increment and decrement operations are not that trivial. When the increment/decrement operation is to the left of the variable, you carry the operation before using the variable. When the increment/decrement operation is to the right of the variable, you first use the variable in its other operation and only then carry the increment/decrement operation. You notice the effect of this operation just before the second attempt to use the variable.
Let's work the numbers in the example above. The variable
number is initialized to 0. Next,
number is assigned -2. The right hand side increment operation is not immediately felt, so the first parenthesis evaluates then to -2. The right pair of parenthesis starts with
number equal to 1 due to the late incrementing of
number from 0 to 1. Then,
number is decremented to 0 by the left hand side decrement operation and the whole term evaluates to -1. We have a multiplication of -2 by -1 which yields 2, so
answer is 2 at the end of the second statement. The last statement assigns
number is now 2 and that's what will be printing. The later incrementing will increment
answer to 3 at the exit of the script.
The following script is longer, but definitely much clearer:
number = 0; answer = number - 2; number++; number--; answer *= number - 1; number = answer; document.write(number); number = answer; answer++;