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 -
|
|
I fondly remembered my good ol’ days with Python, and then thought about two things -
- Why do people not use Google?
- 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.
|
|
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
.
|
|