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 Iterating through an Array

Can you help me with this code

Is this code correct or I type it wrong

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

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

What is your error?

please click on the view challenge on the top right of the page

console.log(temperatures[i]);

if you want to loop through the temperatures this is what you'd do

3 Answers

Steven Parker
Steven Parker
229,744 Points

:point_right: The challenge wants only one item logged at a time.

Your code logs the entire array each time through the loop. Try selecting just one of the items to log:

  console.log(temperatures[i]);

thanks for helping me out

Erik Nuber
Erik Nuber
20,629 Points

The way it is written right now, it is simply logging the entire array to the console 8 times. To fix it so that it puts each temperature individually you would change this statement

console.log(temperatures[i]);

That is if what you are trying to achieve is an iteration thru the array itself.

thanks

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,858 Points

Hey Sudhir,

Your really close. In the console log, the code is just logging temperatures as the entire array. Using the i variable from the loop, you need to log each item in the array separately.

So, it's just one little change you need to make to log out each array item as the loop moves forward.

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

Notice the [i] appended to the end the temperatures value. This now takes the value of i and calls the appropriate item in the array. I hope that helps.

:dizzy: