Hemanth's Scribes

javascript

Negative Array Index in JavaScript

Author Photo

Hemanth HM

Thumbnail

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

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
#javascript#es6#proxies
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.