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 Introducing the Practice

Loops in Arrays.

```JS/* INSTRUCTIONS To run this file, click in the Console below and type: node 2_loop.js If the console isn't visible, click the View menu above and choose Show Console.

You can clear the console by typing clear and pressing enter.

If your program is stuck in an infinite loop, you can break out of the program by typing ctrl + C. */

/*Note: We've supplied you a basic function for generating a random number from 1 to 100 */ function random100() { return Math.floor(Math.random() * 100) + 1; }

/* 1. Create a function named createRandomList that uses a for loop to create an array containing 10 random numbers from 1 to 100 (use the supplied function above to generate the numbers). The function should return that array. */ function createRandomList() { for (i = 0; i < 10; i++) { console.log(createRandomList[i]); } }

/* 2. Call the createRandomList() function and store the results in a variable named myRandomList. */

function createRandomList() {

}

/* 3. Use a for loop to access each element in the loop. Each time through the loop log a message to the console that looks something like this: Item 0 in the array is 48 When you're done you should have output 10 lines to the console -- one for each element. */

// Run your code by typing node 2_loop.js in the console below```

CAN SOME ONE JOG MY MEMORY ON HOW TO USE A LOOP IN AN ARRAY?

1 Answer

Steven Parker
Steven Parker
229,582 Points

The loop itself is similar to the one you created to build the array. But this time, you'll use the length of the array as the limiting condition. You could also use "10" again, since you know that is the length of the array; but it's more generic and a good practice to use the actual length:

for (var i = 0; i < myArray.length; i++)

Then, inside the loop, you can use the loop variable as an index to the specific item: "myArray[i]".

Also, if you just hang on for 2 more videos, an example will be shown and explained in Array Iteration with a For Loop.

Thank you again. Do you have any tips on how I can excercise the skills needed to build thise loops and arrays?

Steven Parker
Steven Parker
229,582 Points

Creating your own projects might be the best practice, plus there are these workshops: Practice JavaScript Loops and Practice Basic Arrays in JavaScript.