Changes

Jump to: navigation, search

JavaScript Operators

1,298 bytes added, 20:04, 19 April 2007
Arithmetic Operators
<td>%<td>Modulus - Divides left hand value by right hand value and returns remainder</td>
</table>
 
=== Incrementing and Decrementing Values ===
 
In JavaScript programming it is extremely common to need to incremement and decrement values assigned to variables. The long handed way fo doing this would be:
 
<pre>
 
x = 10;
 
x = x - 1; // Decreases value of x by 1
 
x = x + 1; // Increase value of x by 1
 
</pre>
 
A quicker way to perform this is to use the ++ and -- operators. The syntax for this is as follows:
 
<pre>
 
--x; // Decreases value of x by 1
 
++x; // Increase value of x by 1
 
 
</pre>
 
These operators can also be used increment and decrement a value after an expression as been performed. Suppose you have a varable ''x'' which has been assigned a value of 5. You want to add the value of x to a varable called y and then decrement x by 1. One way to do this is as follows:
 
<pre>
 
var x = 5;
var y = 10;
 
y = y + x; // assigns the value 15 to variable y
++x; // adds 1 to x to make it 6
 
</pre>
 
By placing the operator after the variable name the variable is automatically incremented or decremented immediately after the expression as been evaluated:
 
<pre>
 
var x = 5;
var y = 10;
 
y = y + x++; // value of y is now 15, value of x is now 6
 
// Note that the above exression can be further shortened as follows:
 
y += x++ // value of y is now 15, value of x is now 6
 
</pre>

Navigation menu