There is a HUGE difference between
x++ (known as POST-increment)
and
++x (known as PRE-increment)
and I'm more than a little surprised that the book you are using doesn't both explain it carefully and show specific examples.
I can't write a chapter in a book here, but let's see if we can make sense of this.
Let's start by explaining x++ vs. ++x.
It is true that AT THE END OF THE STATEMENT, both will have had the same effect on x. But WITHIN THE EXPRESSION that uses one or the other, the difference is clear:
++x means "first increment x and then get its value for use in the surrounding expression."
x++ means "first get the value of x and use that UNINCREMENTED value in the surrounding expression; THEN AND ONLY THEN increment x."
So in your example:
Code:
num = 2;
alert(num); // added for clarity
secnum = num++;
alert(num);
alert(secnum);
Indeed
num is initialized to a value of 2, as the first alert (as I added it) reveals.
So the next line is the secret.
secnum = num++;
Now, recall what I wrote above: The increment of num takes place AFTER ITS NON-INCREMENTED VALUE is used in the expression.
In other words, it is just as if you had done:
secnum = num;
++num; // as a separate step!
So you can clearly see that, BEFORE the increment,
num has a value of 2 and THAT is what is copied into
secnum. And then only AFTER that is
num incremented to the value 3.
Okay??
**************************
Now, we have to be a *little* careful. I wrote that doing
secnum = num++;
is the same as
secnum = num;
++num;
But that's not strictly true. If you use the variable
num *again* in the same expression, you will find that indeed it *HAS* been incremented.
It is instructive, perhaps, to try this code:
Code:
num = 13;
secnum = num++ + num;
alert(num);
alert(secnum);
Can you make sense of that???
In this statement:
secnum = num++ + num;
what actually happens is
13 [the existing value of num] is used as the left hand value for the + operator that is still to come.
num is bumped up to 14
14 [the now changed value of num] is used as the right hand value for the + operator.
secnum gets the value 27.
So if you only use a post-incremented variable one time in a statement, then indeed you can treat it as if the increment happens after the statement is complete. It's only those rare occasions when you see the variable being used more than once that you have to be careful.
Okay?
So now test yourself:
num = 101;
secnum = ++num + num++;
what is the value of num? what is the value of secnum?