Is a JavaScript array index a string or an integer?

user3033194 picture user3033194 · Dec 18, 2014 · Viewed 12.6k times · Source

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.

Answer

Pointy picture Pointy · Dec 18, 2014

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).