0

This is my JavaScript array code for negative index number. In output why doesn't consider negative index number in the count of the element? It shows only count (3) in output.

Code

let abc = ['gnagar', 'ahmedabad', 25];
console.log(abc, typeof(abc));
console.log(abc[-1]);
abc[-1] = 'abc';
console.log(abc, typeof(abc));
console.log(abc[-1]);
Kobe
  • 6,226
  • 1
  • 14
  • 35
Ankit Modi
  • 11
  • 2
  • 5
    Because `array` starts from 0 – Shubham Dixit Dec 13 '19 at 08:56
  • These indexes are non-negative integers and Starts from 0 check https://stackoverflow.com/questions/13618571/should-negative-indexes-in-javascript-arrays-contribute-to-array-length – Rakesh T.R Dec 13 '19 at 09:01
  • 1
    Seems like [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - what is the problem that you're trying to solve with a negative index in an array? – VLAZ Dec 13 '19 at 09:01

2 Answers2

1

-1 is not a valid index for array.

The assignment abc[-1] = 'abc'; means set attribute "-1" to the abc object.

keshin
  • 534
  • 4
  • 8
0

This is because array is type of object as you can see there typeof(abc) is object.

You can assign values in objects using [].

Negative indexes are not actual index so it does not impact the array length.

Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51