Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why javascript array element can't be accessed with dot notation?

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?

like image 820
Yukulélé Avatar asked Jul 08 '15 20:07

Yukulélé


2 Answers

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.

like image 166
Lightness Races in Orbit Avatar answered Nov 08 '22 23:11

Lightness Races in Orbit


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

like image 43
PaulShovan Avatar answered Nov 09 '22 00:11

PaulShovan