I might be being a bit thicky here but please answer me this. Consider the following code:
a=1;
while(a<=6) {
console.log(a);
a++;
}
If I run this I get values in the console from 1 to 6, and then another 6.
Now look at this:
a=1;
while(a<=6) {
console.log(a);
++a;
}
Running this will now get me the values from 1 to 7.
Why is this happening? My understanding was that the statement block would only run if the expression evaluates to true. How can this be possible in the second of my examples? And why does 6 appear twice in the first? Very confusing for me.
If you can explain simply (I’m still learning) that would be great.
The console prints for you the value of the last statement evaluated. In the second case, you pre-increment, so the value of that is 7 and not 6 as in the first one.
Change you
console.log()call to print more stuff and it’ll be obvious:You won’t see that prefix on the last line.