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 Arrays Loop Through Arrays Loop Through an Array

Why my code is incoorect? what the [i] inside the console.log. works?

Thank you

script.js
const temperatures = [100, 90, 99, 80, 70, 65, 30, 10];
for (i = 100, i >=10, i -- ) {
  console.log (temperatures[i])

2 Answers

Hi Hanwen!

A few issues:

You have commas in the for-loop condition when they should be semicolons.

Make sure to declare i with let.

I think you are confusing the array values with the ordinal positions (represented by i)

For example, the value 100 is in the first ordinal position in the array, whereas the value 10 is in the last.

In other words, temperatures[0] == 100 and temperatures[7] == 10 (7 being temperatures.length - 1)

So this is what will pass:

const temperatures = [100, 90, 99, 80, 70, 65, 30, 10];
for (let i = 0; i < temperatures.length; i++ ) {
  console.log (temperatures[i])
}

And it will loop 8 times, giving you i values of:

0, 1, 2, 3, 4, 5, 6, 7

And the console will log:

100
90
99
80
70
65
30
10

I hope that helps.

Stay safe and happy coding!

Hi Peter,

Thank you, you made it so easy to understand. I appreciate it.

By the way,

You can test it here:

https://www.w3schools.com/js/tryit.asp?filename=tryjs_array

Copy and paste this code in the left pane (replacing the existing code):

<!DOCTYPE html>
<html>
<body>

<h2>Temps</h2>

<script>
const temperatures = [100, 90, 99, 80, 70, 65, 30, 10];
for (let i = 0; i < temperatures.length; i++ ) {
  console.log (i);  // I added this for clarity
  console.log (temperatures[i])
}
</script>

</body>
</html>

And then right-click in the right pane to get to the console to see the results.

Again, I hope that helps.

Stay safe and happy coding!