Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Iterating through an Array

How do you do this question? I don't understand how to incorporate the temperatures array correctly.

What am I doing wrong here?

script.js
var temperatures = [100,90,99,80,70,65,30,10];

for (i = 0; i < temperatures.length; i += 1) {
 console.log(i); 
}
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

3 Answers

Logan R
Logan R
22,989 Points

You're mostly there!

To get the value from an array, you must first do the name of the array, followed by the offset in [].

So for example:

var myArray = [10, 40, 50]

So say that I wanted the 40 from the array. I would get this by using an offset of 1 (Starting from 0):

console.log(myArray[1]);

So in this instance, you want an offset of i.

Does that make sense?

Hmmm but how do you log the array out in order then? Whats the syntax for that?

Amos Dailey
Amos Dailey
17,561 Points

Inside your loop you will log the array out using the var "i" as the counter.

So the first time through the loop, "i" will be 0. then it hits console.log(temperature[i]); ///Which is the same as console.log(temperature[0]);

And on the next iteration through the loop "i" will be one. So... console.log(temperature[i]); ///Which is the same as console.log(temperature[1]);

And so on till you get to the length of the array.