|
November 22, 1999 Avoiding Side Effects Tips: November 1999
Yehuda Shiran, Ph.D.
|
|
A side effect is an operation performed in addition to the main one. Take a look at the following statements:
The first line is a simple assignment statement. The second line is a bit more complicated. It performs two actions in the following order:
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. The assignment operation can also be accomplished as a side effect. Consider the following JavaScript statement:
This statement prints
See if you can figure out the result this code:
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 The following script is longer, but definitely much clearer:
People who read this tip also read these tips: Look for similar tips by subject: |