Short Answer:
Because there is no element at the index 0
of array
, and in more generic words, the property 0
is not defined in variable array
. Therefore calling a property on something that is not defined would give you an error.
Long Answer:
Consider all JavaScript objects as dictionaries, and lets think that these dictionaries return us the values if we provide the keys that exist in them, otherwise nothing is returned.
Therefore when accessing an object property like myObject.propA
(which is same as myObject["propA"]
), if it exists in this object then the value of that property is returned and if not then undefined
is returned, which denotes that this property is not defined in the myObject
.
An array ([]
) in JavaScript is also a type of object, and each member in the array is actually the property of that object. So a property in var arr = ["asd", "fgh"]
can be accessed by arr[0]
or arr["0"]
, which means that if property 0
of arr
exists then it would return the value (in this case "asd"), otherwise would return undefined.
Providing all this, calling a property on something that is undefined is both illogical and illegal, so an exception is raised.