Array
objects cannot use arbitrary strings as element indexes (as in an associative array) but must use nonnegative integers (or their respective string form). Setting or accessing via non-integers will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's traversal and mutation operations cannot be applied to these named properties.
Array elements are object properties in the same way that toString
is a property (to be specific, however, toString()
is a method). Nevertheless, trying to access an element of an array as follows throws a syntax error because the property name is not valid:
arr.0; / a syntax error
JavaScript syntax requires properties beginning with a digit to be accessed using dot notation. It's also possible to quote the array indices (e.g., years['2']
instead of years[2]
), although usually not necessary.
The 2
in years[2]
is coerced into a string by the JavaScript engine through an implicit toString
conversion. As a result, '2'
and '02'
would refer to two different slots on the years
object, and the following example could be true
:
console.log(years["2"] !== years["02"]);
Only years['2']
is an actual array index. years['02']
is an arbitrary string property that will not be visited in array iteration.