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, Arrays and Objects Simplify Repetitive Tasks with Loops Complete the Loop

John Erickson
seal-mask
.a{fill-rule:evenodd;}techdegree
John Erickson
Full Stack JavaScript Techdegree Student 3,916 Points

Loop executes, however provides the same random number rather than varying numbers.

I finished watching the, "What are Loops" video and I can easily get the loop to work when I match letter for letter, word for word what Dave provides, however when I attempt to do it on my own it doesn't work properly. Below is my code. I get a random number, however that number repeats 10 times, so for example if the random number is 5, I get 10 repeated 5s.

I've gone through the code and the logic makes sense. I know it's not a syntax issue or the code would not run, which it does.

I create a random number stored in the variable randomNumber. I tested to see that it works, providing a different random number each time and it does (see comment). I create a variable named counter as a start point. The while loop is less than 10, so the code block runs, writing a random number to the document. The counter adds 1 and the loop starts over. My only problem is the results are the same random number repeated.

Any help would be greatly appreciated.

Thanks, John

script.js
var randomNumber = Math.floor( Math.random() * 10 ) + 1;

// console.log( randomNumber ); - Check to make sure randomNumber works, which it does

var counter = 0;
while ( counter < 10 ) {
document.write( randomNumber );
counter += 1;
}

1 Answer

hello, you're close. you just need to create the randomNumber variable inside the loop so that you get a new number each iteration.

counter = 0;
while  ( counter < 10 ) {
var randomNumber = Math.floor( Math.random() * 10 ) + 1;
counter += 1;
console.log( randomNumber );
}