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 Using Array Indices

David Curran
David Curran
7,682 Points

Accessing the last item in an array

why is this code not working var players = ['Jim', 'Shawna', 'Andrew', 'Lora', 'Aimee', 'Nick']; console.log(players[5]);

script.js
var players = ['Jim', 'Shawna', 'Andrew', 'Lora', 'Aimee', 'Nick'];
console.log(players[5]);
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

Um... Actually players[5] is a valid index. It does point to the last element in the array.

Look at this chart of the players list:

'Jim', 'Shawna', 'Andrew', 'Lora', 'Aimee', 'Nick'
 0,     1,        2,        3,      4,       5

As you see, the last items is at index 5.

David Curran
David Curran
7,682 Points

Thanks for your help Alexander, I'm confused to why the code is not passing. The index is 5 so the code should pass. Not sure whats going on.

I see what's wrong in your code.

Did the challenge ask you to remove the code you wrote in the last task?! Heck no. Don't remove the code from the previous task unless the challenge asks you to!

~Alex

David Curran
David Curran
7,682 Points

Nice work Alexander, your answer helped. Thank you. I was removing the previous console.log(players[0]); when I shouldn't have been. Thanks again.

remember array are zero indexed.

so it starts from 0.

Jim is 0 Shawna is 1 Andrew is 2 etc...

David Curran
David Curran
7,682 Points

Thanks for your help Ruhull, I understand the concept of indexing, although the code still isnt passing.