Arrays are special objects. But the usability of dot notation doesn't depend on the object, but rather the property you want to access.
Also note that foo.bar
is the same as foo['bar']
.
You can always use bracket notation. On the other hand, dot notation can only be used if the property is a valid identifier (consists of letters, numbers, $
s and _
s, and can't begin with a number).
That shows the reason why we can't access arrays' indices with it, as they are numbers (so they also begin with numbers).
The bracket notation is also required if you want to access a key named the result of evaluating an expression.
So:
const object = {
0: 1,
foo: 2,
'key with spaces': 3,
'3D': 4,
'D3': 5
}
const array = [1, 2, 3]
//These are okay...
object.foo
object['foo']
array.reduce
array['reduce']
object[0]
array[0]
object['0']
array['0']
object['key with spaces']
object['3D']
object.D3
object['D3']
object['f' + 'o'.repeat(2)]
array[array.length-2]
//...but these are not:
object.0
array.0
object.key with spaces
object.3D //begins with a number