6

Why can't we use integer keys in dot expression to access property values ?

var obj = {1: 'one', two: '2'}
console.log(obj.1) // error
console.log(obj.two)
2
  • 3
    I think due to the limitation of naming convention of javascript variable. Commented Apr 27, 2015 at 6:03
  • 1 is represented as string internally. Commented Apr 27, 2015 at 6:06

3 Answers 3

13

In case of dot notation to access a value, the property key must be a valid identifier

In this code, property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.

You can use bracket notation in this case

obj['1']

Spec: Property Accessors

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

2 Comments

The last link is broken.
0

Adding to @Arun P Johny' s answer we can use obj['1'] with quotes or obj[1] without quotes in case of integer. where as accessing obj['two'] will work but obj[two] will throw an error if there is no variable/constant as two.

Comments

-2

It is a JavaScript base princible which says variables cannot start with a number. Over here the property is a variable and hence it cannot start with a number.

You can check more about variable definition rules here

Hope this helps.

3 Comments

This link is broken.
Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference since it is now dead
Property names are not variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.