Why it's not possible to access to array element with dot notation?
var arr = ['Apple', 'Mango', 'Pineapple', 'Orange', {name: 'Banana', color: 'yellow'}];
console.log( arr[0] ); // "Apple"
console.log( arr.0 ); // "Apple"
console.log( arr.3 ); // "Orange"
console.log( arr[4].name ); // "Banana"
console.log( arr.4.color ); // "yellow"
In other words, why language designers have chosen to forbid identifiers starting with number?
Because identifiers are not allowed to start with numbers, and the y
in x.y
is an identifier.
Why is the y
in x.y
an identifier? No idea. Ask the language designers on the appropriate mailing list or in an AMA session. I'd guess that it makes both language specification and interpretation wildly easier.
according to javascript's nature an object's property name can be defined as following...
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). more...
As array's property name starts with number it can only be accessed using square([])
brackets
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.
So, in case of dot notation it looks for a string inside of the object and it never casts the value given after dot(.) notation. For this reason obj.1
is not valid and actually does not exist. On the other hand, in case of square([]) brackets the value is always casted into string to find the property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With