JavaScript Operator: decrement
[this page | pdf | back links]
In JavaScript,
the -- operator is
the (unary) arithmetic operator for decrementing, i.e. subtracting one from the
variable.
There are technically two
different decrement operators, the prefix one, and the postfix one. For
example, if x is 8 then the statement y = --x results in x being decremented to 7 and then y assigned this value (i.e.
is assigned 7). However, the
statement y = x-- involves y being assigned the value of x (i.e. 8)
and x then being decremented to 7.
For code clarity, some
commentators suggest using the statements x
= x - 1; y = x; instead of y = --x
and y = x; x = x - 1; instead of
y = x--.
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>table,th,tr,td {border: 1px solid black;
border-collapse: collapse;}</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
<th>Resulting value of <code>y</code></th>
</tr>
<tr>
<td><code id="DecrementPrefixExample"></code></td>
<td><code id="DecrementPrefixx"></code></td>
<td><code id="DecrementPrefixy"></code></td>
</tr>
<tr>
<td><code id="DecrementPostfixExample"></code></td>
<td><code id="DecrementPostfixx"></code></td>
<td><code id="DecrementPostfixy"></code></td>
</tr>
</table>
<script>
document.getElementById("DecrementPrefixExample").innerHTML =
'var x = 8;<br>' +
'var y = --x;';
var x = 8; var y = --x;
document.getElementById("DecrementPrefixx").innerHTML = x;
document.getElementById("DecrementPrefixy").innerHTML = y;
document.getElementById("DecrementPostfixExample").innerHTML =
'var x = 8;<br>' +
'var y = x--;';
x = 8; y = x--;
document.getElementById("DecrementPostfixx").innerHTML = x;
document.getElementById("DecrementPostfixy").innerHTML = y;
</script>
</body>
</html>
|
NAVIGATION LINKS
Contents | Prev | Next | JavaScript Operators