++ not the same as += 1?

Hey guys, so I am going through the JS course at the moment and have a little question regarding loops.
When I run

var ten = 0;
while(ten <= 10) {
console.log(ten);
ten += 1;
}

I’ll get the console to print the numbers 1 to 11.

But when I run

var ten = 0;
while(ten <= 10) {
console.log(ten);
ten++;
}

I’ll get the console to print the numbers 1 to 10.

I thought

ten += 1;

should be the same as

ten = ten + 1;

am I doing / thinking something wrong here?

2 Likes

Hey @jott, hope you are great man.

Now your code works for me, the console show me the numbers from 0 to 10.

Now using ten += 1 OR ten = ten + 1 OR ten++ works the same for me, meaning, same result.

IF you want to show from 1 to 10, the variable ten should start at 1, then it will start showing 1.
your while condition is (ten<=10), this mean ten less than or equal to ten. So it will go one iteration more when it goes to 10, showing the 11, but when iteration start again, condition will break because 11 is greater than 10.

To fix this just take in mind that there is a difference between < and <=, second one will run one iteration more even when the number is equal to the condition, because it allows to run another iteration when the variable is equal to condition.

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

Hi @thecil, thank you for this awesome explanation - helped a lot!
Which program are you using for executing JS? Maybe it’s Chrome’s fault (already read that Chrome sometimes has a hard time doing so).

I usually verify on multiple browsers console, Brave, Firefox, Chrome, Vivaldi, Opera, if one shows me a weird result, I just run the same code on different browsers, just to verify that result is calculated in the same way from all of them (because it should be calculated the same way no matter which i use) :nerd_face:

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

@jott it looks like you’re getting confused a bit here. Apart from printing the value of ten variable via console.log(), the console also prints out the result of the last operation (ten += 1 or ten++ in this case). You think that 11 and the second 10 are printed via console.log(), but they are not. You can see it if you run the following code:
var ten = 0, test;
while(ten <= 10) {
console.log(ten);
ten++;
test = 0 * ten;
}
and
var ten = 0, test;
while(ten <= 10) {
console.log(ten);
ten += 1;
test = 0 * ten;
}
The output is the same.