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

There must be a easier way to do this?

I'm trying to build a random password generator using arrays. Loops have always baffled me and I know there is a simple way to do it. Can someone help a lost soul and put this into a loop for me!

 btn.addEventListener('click', () => {
       var randomNumber1 = Math.floor((Math.random() * 10));
       var randomNumber2 = Math.floor((Math.random() * 10));
       var randomNumber3 = Math.floor((Math.random() * 10));
       var randomNumber4 = Math.floor((Math.random() * 10));
       var randomNumber5 = Math.floor((Math.random() * 10));
       var randomNumber6 = Math.floor((Math.random() * 10));
       var randomNumber7 = Math.floor((Math.random() * 10));
       var randomNumber8 = Math.floor((Math.random() * 10));
       var randomNumber9 = Math.floor((Math.random() * 10));

    })

2 Answers

Hi Nick

There are a bunch of different loops you can use to do this, the most simple one I think to understand is the for loop.

You display the same code every time apart from the number increments, we can do this with a for loop

Use the for loop to increment the var number

btn.addEventListener("click", () => {
     // Create an empty array where we will store our variables
    let randomNumber = []; 

   // Loop through the array incrementing the counter, "i"
    for ( let i = 0; i < 10; i++ ) { 

        // Add a randomly generated number to each increment of the counter, "i"
        randomNumber[i] = Math.floor((Math.random() * 10));   
    }

    // And for testing purposes, you can see the randomly generated numbers
    console.log(randomNumber); 
 });
  1. So in this for loop the counter starts at 0,

  2. it checks if 0 < 10 which is true

  3. it will say randomNumber[0] = the random number,

  4. it then increments the counter by one and starts again

  5. So in the next loop the counter is 1,

  6. it checks if 1 < 10 which is true

  7. it will say randomNumber[1] = the random number,

  8. it then increments the counter by one and starts again

and so on...

Tidy solution

btn.addEventListener("click", () => {
    let randomNumber = []; 
    for ( let i = 0; i < 10; i++ ) { 
        randomNumber[i] = Math.floor((Math.random() * 10));   
    }
 });

Hope this helps

Good luck!

Hi Liam,

Worked like a charm!

Thanks