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 A Closer Look at Loop Conditions

Mario Martinez
Mario Martinez
7,097 Points

Wrote it different and seems to work. But cant be certain

var upper = 10000; var counter = 0;

function getRandomNumber(upper) { return Math.floor( Math.random() * upper ) + 1; }

while (getRandomNumber(upper) !== num){ counter += 1; var num = Math.floor( Math.random() * upper ) + 1; } console.log(getRandomNumber(upper)); console.log(counter);

1 Answer

Steven Parker
Steven Parker
231,275 Points

Other than repeating the code from the function inside your loop, the main difference is that the video code picks a number one time, holds on to it, and then tries repeatedly to match it. But your code doesn't hold a picked number and instead picks two numbers repeatedly until it gets two that are the same.

Apparently the odds of picking the same number twice in a row are similar to the odds of matching a previously picked number, so the difference isn't obvious from the outcome.

Also at the end, you display yet another random pick that is unrelated to what the loop did.

Steven Parker
Steven Parker
231,275 Points

This code picks a random number into the variable "num", and compares it with another random number from calling "getRandomNumber". This is done over and over in a loop until they both have the same value.

Note that when the loop performs the test the first time, "num" has not been assigned yet and will be undefined.