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

Kieran Barker
Kieran Barker
15,028 Points

What's wrong with my loop?

Am I just stupid? I tried to apply the same technique as taught in the video... But apparently it's not doing it in order. Why isn't it!? It's exactly the same! I think I'm just dumb.

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

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

I solved it myself... The counter variable has to be initialised at 0. Presumably that's because arrays are zero-indexed?

Yep that's because your arrays first value is always located at Zero(0) index and onward.

1 Answer

Steven Parker
Steven Parker
229,732 Points

You're quite right, the first element of an array has an index value of 0.

And the last element index is one less than the array length.

var nums = [  1,  2,  3,  4,  5 ];
//            ^               ^
//            nums[0]         nums[4]
Kieran Barker
Kieran Barker
15,028 Points

Thank you, Steven, particularly for the snippet about the last element's index value being one less than the length of the array. But how does that knowledge help me?

Steven Parker
Steven Parker
229,732 Points

You might want to loop through an array by index. So you'd start the index at 0, and end it before it reaches the length:

for (var i=0; i < nums.length; i++) {  // note < instead of <=
    doSomethingWith( nums[i] );
}