JavaScript Operators - Add and Assign
(Page 4 of 6 )
The add and assign operator works like this: a = a + y is the same as writing a += y. Or like this:
<HTML>
<HEAD>
<script type="text/Javascript">
a=10
y=5
line = '<br>'
document.write(a)
document.write(line)
document.write(y)
document.write(line)
a += y
document.write(a)
</SCRIPT>
</HEAD>
</HTML>
The above code prints out:
10
5
15
First we assigned a value to a (10), then we assigned a value to y (5) and printed them both out with a line break (which we cleverly stored in a variable). We then added the two variables together using the += operator, and printed the new value of the variable a.
It works the same way with the other arithmetic assignment operators as well. Had I used *=, the final value of a would have been 50. If I had used the /= it would have been 2, and had I used the %= it would have been 0, since there is no remainder in the expression 10 / 5.
Next: Comparison Operators >>
More JavaScript Articles
More By James Payne