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!

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]);

var players = ['Jim', 'Shawna', 'Andrew', 'Lora', 'Aimee', 'Nick'];
<!DOCTYPE html>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
<script src="script.js"></script>

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!


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.