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.
A similar way to set up a while loop is with a do… while . A do… while statement is similar to a while loop in the fact that it will continue to run until the condition becomes false.
A for loop is more structured than the while loop.
while — loops through a block of code once; then the condition is evaluated. If the condition is true, the statement is repeated as long as the specified condition is true. for — loops through a block of code until the counter reaches a specified number. for…in — loops through the properties of an object.
The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.
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:
console.log("a is: " + a);
You won't see that prefix on the last line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With