JavaScript Operators - Arithmetic Operators
(Page 2 of 6 )
We've been working with Arithmetic operators since we were children. In JavaScript they work pretty much the same way they did then. Observe:
<html>
<body>
<script type="text/Javascript">
var youweigh = 200
var yourmommaweighs = 400
var linebreak = "<br/>"
document.write("Your weight: ")
document.write(linebreak)
document.write(youweigh)
document.write(linebreak)
document.write("Your mother weighs: ")
document.write(linebreak)
document.write(yourmommaweighs)
totalweight=youweigh + yourmommaweighs
document.write(linebreak)
document.write("Your total weight is: ")
document.write(linebreak)
document.write(totalweight)
</script>
</body>
</html>
The above code insults your mother. Or maybe it doesn't. I mean if she weighs more than four hundred pounds, I guess it could be considered a compliment. At any rate, the above code assigns two variables a value. First, a variable named youweigh is assigned the value 200. Then a variable named yourmommaweighs is assigned the value 400. The program then goes through a process of printing out first the amount you weigh, and then the amount your mother weighs. Then, at the end, it uses the + operator to add the two weights, and print out your combined weight. The result of running the above code:
Your weight:
200
Your mother weighs:
400
Your total weight is:
600
A Note about the Modulus
For a while I found the Modulus to be confusing. No one ever adequately described what it did or what it was, despite the fact that it is very simple to define. Basically, modulus returns the remainder in division. Like so:
<html>
<body>
<script type="text/Javascript">
var valueone = 5
var valuetwo = 2
var linebreak = "<br/>"
modresult = 5 % 2
document.write(modresult)
</script>
</body>
</html>
The above code takes the variable valueone, assigns it the value of five, then takes the variable valuetwo and assigns it the value of two. Finally, we store the modulus in modresult, and print it. Since 5 / 2 equals 2 with a remainder of 1, we end up printing the 1 (the remainder or modulus).
Next: Assignment Operators >>
More JavaScript Articles
More By James Payne