JavaScript Operators - Assignment Operators
(Page 3 of 6 )
We worked with the "=" assignment operator when we went over variables. As the name suggests, assignment operators assign a value. Where they can get tricky is in the pre/post area. When you use an assignment variable in the position before the variable, it is added prior to the line being executed. When you use it after the variable, it is added afterward. Sound confusing? This should clear it up.
<HTML>
<HEAD>
<script type="text/Javascript">
a=10
b=6
document.write('Angelina Jolie is '+a+++', and in ten years will be an '+a)
document.write('<BR>Jennifer Lopez is a '+--b+', and in ten years will be a '+b)
</SCRIPT>
</HEAD>
</HTML>
In the above sample I rated the current hotness and predicted future hotness of Angelina Jolie and Jennifer Lopez. As you can see, I don't think J-Lo is very hot. I used the increment (++) operator to increase the hotness of Angelina Jolie by one. Since the ++ appeared after the variable name, it prints 10 instead of eleven in the first part of the sentence, then it increments the value by one, and prints eleven at the end of the sentence. This is the result:
Angelina Jolie is 10, and in ten years will be an 11
Jennifer Lopez is a 5, and in ten years will be a 5
If I had put the ++ at the beginning of the variable, it would have read this way:
Angelina Jolie is 11, and in ten years will be an 11
Jennifer Lopez is a 5, and in ten years will be a 5
It works the same way with the - decrementing operator. As you can see in the J-Lo example, it subtracted 1 from the value of b prior to printing the variable.
Next: Add and Assign >>
More JavaScript Articles
More By James Payne