Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about while loop in javascript

Tags:

javascript

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.

like image 446
Mat Richardson Avatar asked Jun 26 '12 16:06

Mat Richardson


People also ask

What is similar to a while loop?

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.

What is better than while loop?

A for loop is more structured than the while loop.

What is the difference between for loop and while loop in JavaScript?

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.

What are while loops used for in JavaScript?

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.


1 Answers

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.

like image 169
Pointy Avatar answered Sep 24 '22 23:09

Pointy