2

Why does a Javascript array accept a string as an index, and when it accepts any string value as index then why doesn't it change its length?

I am new to Javascript and encountered this issue.

var newArr = [];
newArr[0] = 0;
newArr[1] = 1;
newArr["2"] = 3;
newArr[3] = 3;
newArr[4] = 4;
newArr["a"] = "a";
console.log(newArr);
(5) [0, 1, 3, 3, 4, a: "a"]
length: 5
__proto__: Array(0)
Palle Due
  • 5,929
  • 4
  • 17
  • 32

2 Answers2

4

Because

typeof Array() === 'object'

therefore it is possible to add a new property to an array as you would on any plain object, that does not change the array length because it's not the same as actually adding (push) an element to the array.

Ref

remix23
  • 2,632
  • 2
  • 11
  • 21
1

Why javscript array accepts string as index

All (normal) property keys get coerced to a string during assignment, if they aren't strings already.

newArr["2"] = 3;

is the same as

newArr[2] = 3;

Arrays are objects, and objects accept arbitrary key-value pairs, so

newArr["a"] = "a";

is legal, it's just very strange to do.

The length of an array only checks numeric properties, see here:

The length property of this Array object is a data property whose value is always numerically greater than the name of every deletable property whose name is an array index.

By "array index", it means that the property key is numeric.

Note that it's also possible to have a Symbol key, which is the one case where a property key will not be a string:

const sym = Symbol();
const obj = {};
obj[sym] = 'foo';

console.log(typeof sym);
console.log(obj);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320