This page looks best with JavaScript enabled

Negative number index in Arrays

 ·   ·  ☕ 2 min read

Negative number indexes do not countdown in an array in Javascript.

There was this forum post that asked about why negative numbers do not work “as expected” in an array.

The logic of the question is -

1
2
3
const nums = [1, 3, 5];
console.log(nums[-1]);
// should have been 5, but returns undefined

I fondly remembered my good ol’ days with Python, and then thought about two things -

  1. Why do people not use Google?
  2. Why do I exist in this universe?

The second question was more philosophical in nature, is persistent, and has nothing to do with the question.

So - the answer.

Like some other languages, Javascript does not consider -1 as counting down from the last element of the array. Instead, -1 is the literal key that you can use in the array.

1
2
3
4
5
6
7
const nums = [1, 2, 3];
nums[-1] = 99;

console.log(nums[-1]); // 99
console.log(nums.length); // 3
console.log(nums);
// [ 1, 2, 3, '-1': 99 ]

Since the array does not have the ability to count till -1, it was simply accepted as a property against array. We see 99 as the value of nums[-1] but the array length stays at 3.

If you really want to count down from the last element, just use splice.

1
2
const nums = [1, 2, 3];
console.log(nums.splice(-1)); // 3
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things