1

This code will alert all the properties names in the object a. 0,1,2 and hello.

Object.prototype.hello = {};

var a = [1,2,3];

for ( var number in a ) {
    alert( number)
}

My question is, I can access the property hello by this syntax:

a.hello

But why can't I access a.0 which should be equal to 1. Isn't the array decleration creating "real properties"?

I know that I can access the properties by a[0] and a["hello"]

1
  • 1
    side note: never loop over an array with for...in, that is for objects only. Commented Sep 17, 2012 at 12:33

4 Answers 4

7

It's a syntax limitation. In JavaScript, identifier must not start with number, so 0 is not a valid one. a.0 will then produce syntax error.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so in the for ... in, I don't get the identifers name. So what does I get?
@SimonEdström for ... in enumerates property names, which are arbitrary strings and therefore may or may not be an identifier.
3

Because:

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($);

Comments

2

Items in an array are accessed using the syntax myArray[index]. The dot notation only allows you to access properties whose names are valid identifiers, and the index of an item in an array, being a number, does not qualify. Therefore, you have to use the more lenient bracket notation.

1 Comment

Items in the array are objects in the protoype, you just can't access them with dot notation because they start with a number.
1

JavaScript identifiers cannot begin with a digit. The property that you are trying to access is an identifier inside the object.

You will find here https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals this fragment:

Variables

You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the \uXXXX Unicode escape sequences as characters in identifiers.

Some examples of legal names are Number_hits, temp99, and _name.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.