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

JavaScript JavaScript Loops Simplify Repetitive Tasks with Loops The while Loop

Gerald Susanteo
seal-mask
.a{fill-rule:evenodd;}techdegree
Gerald Susanteo
Front End Web Development Techdegree Student 7,117 Points

looping with while

in the video does the code mean if the final outcome of the random number is 10 it stops? because that will mean 10 < 10 which is false and so does it mean the loop will stop? i dont really understand this. Can someone help me?

2 Answers

Gergely Bocz
Gergely Bocz
14,244 Points

Hi Gerald!

As Guil explained in the video, the length of the loop depends solely on the counter variable. If you want to go through the loop 10 times, you write counter < 10, if you want to go through 100 times, you write counter < 100.

This kind of while loop is essentially a for loop, where the iterator is called counter in this case. As a for loop it would look something like this:

for(let counter = 0; counter < 10; counter++){
 console.log(`The random number is: ${getRandomNumber(10)}`);
}

As i said before, the number of iterations depends solely on the counter variable's value, since that is in the while loop's condition. See:

while(counter < 10)

If we wanted to end the loop when our randomNumberGenerator gets 10, we should do something like this:

while(getRandomNumber(10) !== 10){
 //Do stuff
}

I hope it helps, if you have any questions feel free to ask!

Shakib Promy
PLUS
Shakib Promy
Courses Plus Student 987 Points

The main point here is counter variable starts at '0', not at '1'. If you start the counter variable at '1', you can write 'while (counter <= 10)' then it will loop 10 times too.