Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Negative array indexes with a Proxy in JavaScript

56 A Proxy that gives an array negative indices

hard

xs[-1] is undefined, because -1 becomes the property key "-1". Wrap an array in a Proxy whose get trap makes negative indices count back from the end, while length, join, spread and push all still work. Then find out what assigning to [-1] does.

Stuck? Three hints, smallest first
  1. 1. A property key is always a string or a symbol, so the trap receives "-1", not -1.
  2. 2. Everything you do not handle must be forwarded: Reflect.get(target, key, receiver).
  3. 3. You trapped reads only. An assignment goes through set, which you did not trap.

The answer

const fromEnd = (array) => new Proxy(array, {
  get(target, key, receiver) {
    if (typeof key === 'string' && /^-\d+$/.test(key)) {
      const at = target.length + Number(key);
      return at >= 0 ? target[at] : undefined;
    }
    return Reflect.get(target, key, receiver);   // everything else, untouched
  },
});

const base = ['Yaba', 'Surulere', 'Ojuelegba', 'Ikeja'];
const stops = fromEnd(base);

const negatives = [stops[-1], stops[-2]];
const outOfRange = stops[-9] === undefined;
const positives = [stops[0], stops.length];
const joined = stops.join(' - ');
const spread = [...stops];
const stillAnArray = Array.isArray(stops);

stops.push('Agege');                  // push reads length and writes through the untrapped set
const afterPush = [base.length, stops[-1]];

stops[-1] = 'Mushin';                 // NOT the last element: a property literally named "-1"
const lengthUnchanged = base.length;
const literalKey = Object.hasOwn(base, '-1');
const readBack = stops[-1];
const onTheTarget = base['-1'];

console.log('negatives :', negatives);
console.log('joined    :', joined);
console.log('after push:', afterPush);
console.log('base      :', base, 'plus a "-1" key holding', onTheTarget);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('-1 reads the last element and -2 the one before it', negatives, ['Ikeja', 'Ojuelegba']);
test('a negative index past the start is undefined, not an error', outOfRange, true);
test('positive indices and length are forwarded unchanged', positives, ['Yaba', 4]);
test('so array methods still work, because they read through the same trap', [joined, spread.length], ['Yaba - Surulere - Ojuelegba - Ikeja', 4]);
test('Array.isArray is true: the target is a real array, not an impostor', stillAnArray, true);
test('push mutates the target and the trap sees the new end', afterPush, [5, 'Agege']);
test('assigning to [-1] adds a property named "-1" and leaves length alone', [lengthUnchanged, literalKey], [5, true]);
test('and the get trap now shadows it, so that value is unreachable through the proxy', [readBack, onTheTarget], ['Agege', 'Mushin']);

The reason xs[-1] does not work is not that arrays refuse negative numbers — it is that there are no numbers in property keys at all. -1 is converted to the string "-1", which is not an array index, so it is an ordinary property that happens to be absent. The trap works because it can recognise that string and compute a real index.

Two details separate a working proxy from a broken one. The first is the fall-through: Reflect.get(target, key, receiver) rather than target[key], so length, join, Symbol.iterator and every method still resolve, and a getter further up the chain runs against the right receiver. Forget it and the proxy answers undefined for everything you did not think of.

The second is the last two assertions, and they are the trap. get intercepts reads only. stops[-1] = 'Mushin' goes through set, which is untrapped, so it lands on the target as a genuine property called "-1" — invisible to length, invisible to JSON.stringify on an array, and then permanently shadowed by the very trap that made reads work. A symmetrical proxy has to trap set, has and deleteProperty the same way, which is why Array.prototype.at exists and this does not ship in real code.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.