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]);

3
  • 5
    Because array starts from 0 Commented Dec 13, 2019 at 8:56
  • These indexes are non-negative integers and Starts from 0 check stackoverflow.com/questions/13618571/… Commented Dec 13, 2019 at 9:01
  • 1
    Seems like an XY problem - what is the problem that you're trying to solve with a negative index in an array? Commented Dec 13, 2019 at 9:01

2 Answers 2

1

-1 is not a valid index for array.

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.