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 What is an Array?

Reverse indexing a list

Is there a way to access list items backwards like in python? For example, var list = [1, 2, 3, 4, 5]; console.log(list[0]); This would log the first item, 1 to the console, Why can we not also access the last item in the list by doing something like this: console.log(list[-1]);

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

Unfortunately, JavaScript doesn't do the reverse indexing thing for arrays (which is one of the many reasons I like Python infinitely better :P). The closest you can get is to call array.reverse() and forward-indexing that way. For example:

let test = ["One", "Two", "Three"];

console.log(test[0]); // Logs "One"
console.log(test[1]); // Logs "Two"
console.log(test[2]); // Logs "Three"

test.reverse();

console.log(test[0]); // Logs "Three"
console.log(test[1]); // Logs "Two"
console.log(test[2]); // Logs "One"

Me too.

import antigravity

XD! Thanks for your quick response!