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
174,116 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.

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,609 Points

Hey Steven , Can you explain the meaning of picks two numbers repeatedly until it gets two that are the same?

Steven Parker
Steven Parker
174,116 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.