---
title: "Negative Array Index in JavaScript"
description: "Implementing Python-style negative array indexing using ES6 Proxies. Practical notes and code examples on Negative Array."
url: "https://h3manth.com/scribe/negative-array-index-in-javascript/"
canonical_url: "https://h3manth.com/scribe/negative-array-index-in-javascript/"
markdown_url: "https://h3manth.com/scribe/blog/negative-array-index-in-javascript.md"
publishDate: "2013-10-06T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript","es6","proxies"]
word_count: 99
reading_time_minutes: 1
x_markdown_tokens: 282
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Negative Array Index in JavaScript

> Implementing Python-style negative array indexing using ES6 Proxies. Practical notes and code examples on Negative Array.

If you're from Python or Ruby, you're familiar with negative array indexing where `a[-1]` returns the last element.

## JavaScript's Native Support

```javascript
negArray = [];
negArray[-100] = -100;
negArray.length; // 0
negArray[-100];  // -100

## ES6 Proxy Implementation
javascript
function negArray(arr) {
  return Proxy.create({
    set: function(proxy, index, value) {
      index = parseInt(index);
      return index < 0 
        ? (arr[arr.length + index] = value) 
        : (arr[index] = value);
    },
    get: function(proxy, index) {
      index = parseInt(index);
      return index < 0 
        ? arr[arr.length + index] 
        : arr[index];
    }
  });
}

## Usage
javascript
console.log(negArray(['eat', 'code', 'sleep'])[-1]);
// Would log: sleep
```
