Why are string indices legal in JavaScript arrays?

It is legal:

var arr = [1, 2, 3, 4, 5];
arr['ex1'] = 6;
arr.ex2 = 7;

      

Why? Is it also advisable to take advantage of this behavior?

+3


source to share


1 answer


Because arrays are just objects and objects can have arbitrary properties. You can do the same with any other object, for example. function or regular expression.

Note that ex2

it is not considered an "array index". Only properties with names between 0 and 2 32 -2 are considered array elements.

Is it also advisable to take advantage of this behavior?



Not.It depends. I would argue that it makes the code more difficult to understand, the intent is less clear, and it can be confusing for people less familiar with JS.

But of course, this flexibility can be very powerful as well. You should use it responsibly and probably only if there is no other option.

However, I have not seen a case where adding additional properties to arrays is particularly useful.

+7


source







All Articles