Question on While & For Loops in "Learn Basic JavaScript by Building a Role Playing Game"

Hi everyone! Regarding the captioned course, I would really appreciate if someone can explain to me the logic behind the extracted JavaScript code below.

It seems that both the while loop and for loop are achieving the same thing of generating the required integers. What is the significance of including both in the code?

function pick(guess) {
let numbers = ;
while (numbers.length < 10) {
numbers.push(Math.floor(Math.random() * 11));
text.innerText = "You picked " + guess + ā€œ. Here are the random numbers:\nā€;
for (let i = 0; i < 10; i++) {
text.innerText += numbers[i] + ā€œ\nā€;

Thank you in advance, and happy new year!

The first part you make a an empty array called numbers, and in the while loop it says while the length of the array is less than 10 it will add a random number into the array. So, it will put those numbers in that array until the length is 10. Now, that you have an array with your random numbers the for loop comes into play

The for loop you have starts at 0 and it will print one of the random numbers from the array that was filled up with numbers earlier. Everytime a number is displayed the for loop count (or i) goes up by 1. So, since you have i < 10 the for loop will continue to display those random numbers in your array until i is no longer less than 10

1 Like