HTML and CSS Reference
In-Depth Information
EXAMPLE
5.5
<html>
<head><title>Auto-increment and Auto-decrement</title></head>
<body>
<h3>
<script type="text/javascript">
1
var x=5;
var y=0;
2
y = ++x;
//
add one to x first; then assign to y
document.write("Pre-increment:<br />");
3
document.write("y is " + y + "<br />");
document.write("x is " + x + "<br />");
document.write("-----------------------<br />");
4
var x=5;
var y=0;
5
y=x++;
//
assign value in x to y; then add one to x
document.write("Post-increment:<br />");
6
document.write("y is " +
y
+ "<br />");
document.write("x is " +
x
+ "<br />");
</script>
</h3>
</body>
</html>
EXPLANATION
1
The variables,
x
and
y
, are initialized to
5
and
0,
respectively.
2
The pre-increment operator is applied to
x
. This means that
x
will be incremented
before
the assignment is made. The value of
x
was
5
, now it is
6
. The variable
y
is
assigned
6. x
is
6
,
y
is
6
.
3
The new values of
y
and
x
are displayed in the browser window.
4
The variables
x
and
y
are assigned values of
5
and
0,
respectively.
5
This time the post-increment operator is applied to
x
. This means that
x
will be
incremented
after
the assignment is made. The number
5
is assigned to the vari-
able
y
, and then
x
is incremented by
1
. So
x
is
5
and
y
is
6
.
6
The new values of
y
and
x
are displayed in the browser window. See Figure 5.5.