Confusingly in a while loop in javascript

I might be a little fat here, but please answer me that. Consider the following code:

a=1; while(a<=6) { console.log(a); a++; } 

If I run this, I get the 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 give me values ​​from 1 to 7.

Why is this happening? My understanding was that an expression block would only be executed if the expression evaluates to true. How is this possible in the second of my examples? And why do 6 appear twice in the first? Very confusing for me.

If you just explain (I'm still studying), that would be great.

+7
source share
3 answers

The console prints for you the value of the last evaluated operator. In the second case, you first increase, so the value of this is 7, not 6, as in the first.

Modify the console.log() call to print more material, and this will be obvious:

 console.log("a is: " + a); 

You will not see this prefix in the last line.

+13
source

In both cases, you see an extra digit, because the console displays the result of the last statement in the loop.

If this code is not executed directly in the console, you will not see what seems like an extra digit.

+2
source

See fiddle with their answer. Both come back from 1 to 6.

a ++: It returns the value of a before the increment.

++ a : after the increment, the value of a is returned.

Loops run to 'a' <= 6.

When you run some code on the console, it calculates the value of the variable and prints its value, as well as why you get another 6 and 7 in the output.

Do not worry, when you run this code, you will only get values ​​1-6.

0
source

All Articles