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

Michael Zito
PLUS
Michael Zito
Courses Plus Student 4,073 Points

Lost

Been playing around with this for awhile. Confusing myself even more trying to finding the answer. What am I missing?

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

  for ( var i = 100; i < temperatures.length; i += 10) {
  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>

2 Answers

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

  for ( var i = 100; i < temperatures.length; i += 10) {
  console.log(temperatures);
  }

Michael, I can't seem to pull up the lesson to see what your objective was.

However, I'm going to venture an answer here based on what it appears your intention was.

If you are trying to iterate through the array, you need to reference the index with each iteration of the for loop.

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

notice how I declared i and set it to zero in the for loop. I don't know if using var works within the initialization. That's something to check on. I also wanted to traverse through temperatures so I know the first position in the array is indexed at zero. Also, I want to set it to increment by one, so that it goes through the entire array. You were incrementing by 10 so it started at position 100, and then 110, 120, etc.

You also were just printing the full array when you write console.log(temperatures); It was printing the actual object instead of iterating through it.

I hope this makes sense and answers your question.

Cheers!

Adomas Domeika
Adomas Domeika
6,151 Points

Yes, in the loop you have to declare the variable i using either let or var.

You don't have to. Try this,

for (i=0; i < 3; i++) {
    console.log("hi!"):
}

it works