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 trialDavid Curran
7,682 PointsAccessing 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'];
console.log(players[5]);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
2 Answers
Alexander Davison
65,469 PointsUm... 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.
ruhullalam
14,500 Pointsremember array are zero indexed.
so it starts from 0.
Jim is 0 Shawna is 1 Andrew is 2 etc...
David Curran
7,682 PointsThanks for your help Ruhull, I understand the concept of indexing, although the code still isnt passing.
David Curran
7,682 PointsDavid Curran
7,682 PointsThanks 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.
Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsI 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
7,682 PointsDavid Curran
7,682 PointsNice work Alexander, your answer helped. Thank you. I was removing the previous console.log(players[0]); when I shouldn't have been. Thanks again.