Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Alex Watts
8,396 PointsWhy does this loop give me the value of 2?
Hello,
I have recently been looking at loops; why does the following give me the answer of two. I am a little confused.
var x = 45;
while (x > 2) {
x--;
}
alert(x);
This might be a dumb question, but thanks for your help!
2 Answers
nico dev
20,364 PointsHi Alex Watts,
It is a completely valid question! The thing is you call the alert function after the while loop.
So, the code will only do the while loop (that is, decrease x by a value of 1) without continuing with the rest of the code (that is, with the alert function) until the condition in the while becomes false (that is, until x is no longer higher than 2, or in other words, x = 2). By then only, it will call the alert function and give you the value of x.
Try calling the alert function inside the loop (with a document.write / console.log or alike function). It should do what you are expecting to.
nico dev
20,364 PointsGreat! Glad that helped. :)
Keep it up!
Alex Watts
8,396 PointsAlex Watts
8,396 PointsThanks Nico, this really helped me! As you said I added the alert to the loop and I got the result I was expecting to see :)