antonjs
antonjs

Reputation: 14338

How to access an object property with a numeric key?

Maybe is just a stupid question, but, I would appreciate having an explanation of the following behavior:

var obj = {
    key : "val1",
    123 : "val2"
};

obj.key; // "val1"
obj.123; // Syntax error: missing; before statement
obj[123]; // "val2"

Why obj.key is different from obj.123 although they have been declared both as keys of obj.


Accessing the object literal in this way obj.123 is wrong.

And declaring the object in the following way is correct? The browsers I have tested are IE9, firefox and chrome and for all of them it works fine.

var obj = {
    123 : "val1"
};

Upvotes: 3

Views: 1744

Answers (1)

nnnnnn
nnnnnn

Reputation: 150080

JavaScript will let you use just about any string as an object property name, but when accessing properties with the dot notation you're only supposed to use property names that would be valid JS identifiers - which have to start with a letter, the underscore or a dollar sign. So for property names that don't meet the rules for valid identifiers you have to access them with the bracket notation.

Although the bracket notation works with a number, behind the scenes JS will convert that number to a string.

Upvotes: 5

Related Questions