Is a JavaScript array index a string or an integer?

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

Leave a Comment