concept negative array index in category javascript

appears as: negative array indexes
Secrets of the JavaScript Ninja, Second Edition

This is an excerpt from Manning's book Secrets of the JavaScript Ninja, Second Edition.

If your programming background is from languages such as Python, Ruby, or Perl, you might be used to negative array indexes, which enable you to use negative indexes to access array items from the back, as shown in the following snippet:

Now compare the code that we normally use to access the last item in the array, ninjas [ninjas.length-1], with the code that we can use if our language of choice supports negative array indexes, ninjas[-1]. See how much more elegant this is?

Unfortunately, JavaScript doesn’t offer built-in support for negative array indexes, but we can mimic this ability through proxies. To explore this concept, we’ll look at a slightly simplified version of code written by Sindre Sorhus (https://github.com/sindresorhus/negative-array), as shown in the following listing.

Listing 8.12. Negative array indexes with proxies
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest