Question about decrement and increment computations

Hello,

I finished the W3 Schools Javascript beginners course a while ago, and I passed the test. But there is one thing I don’t understand, and that is the increment and decrement computations under JavaScript Arithmetic Operators on http://www.w3schools.com/js/js_operators.asp.

Could someone explain them to me? I think that y++ means: the next object after y. But then I still don’t understand the computation that follows. And I don’t know at all what ++y means.

Thanks in advance.

Those are parts that come from c, and are of little use now. The reason why they are of little use is that once you begin to write code with them your code becomes difficult to understand, and poorly understood code is bad code.

++y is a pre-increment where y is incremeneted before it is used in a calculation, and y++ is a post-increment where y is incremented after a calculation is done.


var x = 0, y = 2;
x = ++y + y++ - ++y;

What is the value of x, and what does y end up being?
Is the second pre-increment more than or the same as the first pre-increment from the same statement?
How does the value of y change throughout that single calculation?

It’s bloody confusing, that’s what!

It’s hard to easily understand what is happening there, so rewriting should be performed instead.


var x = 0, y = 2;
y += 1;
x = y; // ++y
x += y;
y += 1; // y++
y += 1;
x -= y; // ++y

And then refactor in to easier to understand code.

x = (y + 1) + (y + 1) - (y + 3);
which is
x = y - 1;


var x = 0, y = 2;
x = y - 1;
y += 3;

The first piece of code is a line shorter, but the last piece of code is infinitely easier to understand.

These 2 demos might help:


var count = 0;

if(count++ < 5) {

     // but at this point count now = 1

}

is the same as saying


var count = 0;

if(0 < 5) {

     // but at this point count now = 1

}

but


var count = 0;

if(++count < 5) {

     // but at this point count now = 1

}

is the same as saying


var count = 0;

if(1 < 5) {

     // but at this point count now = 1

}

As soon as count++ or ++count are executed, the value of count is incremented by 1. ++ before count means count is first incremented and the new value is then used as the value of count in the statement and ++ after count means the current value of count is first used in the statement and count is then incremented by 1 after the statement is executed.

Thanks a bunch, guys! I’m in the middle of something that doesn’t allow me the time to sit down for this, which I need, but I will certainly report back to you.

Although I needed http://help.dottoro.com/ljpnvikr.php to understand the matter, I do get it now, and your explanations weren’t far off.

glad you sorted it out.

I thought the explanations in this thread were spot on :slight_smile: