Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a JavaScript array index a string or an integer?

I had a generic question about JavaScript arrays. Are array indices in JavaScript internally handled as strings?

I read somewhere that because arrays are objects in JavaScript, the index is actually a string. I am a bit confused about this, and would be glad for any explanation.

like image 589
user3033194 Avatar asked Dec 18 '14 01:12

user3033194


People also ask

Can an array index be a string JavaScript?

Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.

Can an array index be a string?

Actually, it has very much to do with the question (specifically, yes, you CAN use a string as an index, but not in the obvious way that the original querier wants).

Is index a number or string?

The indexes are stored internally as strings. But it's more common practise to use numbers to access an array by it's index.

What is array index in JavaScript?

JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 .


2 Answers

Formally, all property names are strings. That means that array-like numeric property names really aren't any different from any other property names.

If you check step 6 in the relevant part of the spec, you'll see that property accessor expressions are always coerced to strings before looking up the property. That process is followed (formally) regardless of whether the object is an array instance or another sort of object. (Again, it just has to seem like that's what's happening.)

Now, internally, the JavaScript runtime is free to implement array functionality any way it wants.

edit — I had the idea of playing with Number.toString to demonstrate that a number-to-string conversion happens, but it turns out that the spec explicitly describes that specific type conversion as taking place via an internal process, and not by an implicit cast followed by a call to .toString() (which probably is a good thing for performance reasons).

like image 199
Pointy Avatar answered Sep 19 '22 04:09

Pointy


That is correct so:

> var a = ['a','b','c']
undefined
> a
[ 'a', 'b', 'c' ]
> a[0]
'a'
> a['0']
'a'
> a['4'] = 'e'
'e'
> a[3] = 'd'
'd'
> a
[ 'a', 'b', 'c', 'd', 'e' ]
like image 38
Patrick Gunderson Avatar answered Sep 21 '22 04:09

Patrick Gunderson