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 Tracking Multiple Items with Arrays Using For Loops with Arrays

Mandy Rintala
Mandy Rintala
9,046 Points

iterating through an array objective

I need help with this objective. I don't understand how to combine what we learned about the for and while functions with the new array function. This isn't something he went over in the video so I'm not sure how to go about it or which function would work best for less coding and easier understanding.

Roberto Correale
Roberto Correale
1,539 Points

Hi Mandy,

You can use the for or while loop to iterating trough the array. For example you can use them for printing each value of the array in the console.

var arr = ['a','b','c'];

for ( i=0; i<arr.length; i++)
{
    console.log(arr[i]);
}


var i = 0;
while(i<arr.length) {
    console.log(arr[i]);
    i++;
}
Mandy Rintala
Mandy Rintala
9,046 Points

so if arr is equal to temperatures in the objective does that mean i need to be adding another variable to the task for it to make sense. This has me even more confused than before with your example for this objective.

1 Answer

Roberto Correale
Roberto Correale
1,539 Points

Each element of the array is identified by an index. The first element of the array has index 0, the second element index 1 and so on. you can try it doing this

var temperatures = [10,20,30,8];y
console.log(temperatures[0]); //Print 10
console.log(temperatures[1]); //Print 20
console.log(temperatures[2]); //Print 30

The variable "i" used in the while loop in the first example is used as a counter. Basically it will print in the console each single value inside the array while the value of the "i" is the same of the number of total elements in the array (calculated with arr.lenth).

Hope it is more clean now.