saran
saran

Reputation: 368

key of a JavaScript object must be a string

In JavaScript, if you type

typeof("2")

you should get string.

And if you type

typeof(2)

you should get number.

Now my question is, it is said that when you define an object, the key must be a string.

so this is legal

apple = {"color":"red"}

However, if I change the key to a number wrapped in the inverted commas, it should work as anything inside of inverted commas

apple={"2": "red"}

But If I call the object property, apple.2, this will fail with error Unexpected number.

so am just curious, what am I missing here while defining the objects in JavaScript.

Upvotes: 0

Views: 1574

Answers (1)

Steve Bunting
Steve Bunting

Reputation: 439

An object key must be a string, but JavaScript allows you to assign an object with a number. It's just converted to a string behind the scenes, so:

apple = {2: "red"}

is the same as:

apple = {"2": "red"}

Using dot notation requires a valid identifier. So you can not access the property with apple.2 as 2 is a number, instead, you have to use bracket notation, either apple["2"] or apple[2].

Incidentally, there are other cases which can not be accessed with dot notation, such as:

apple = {"hyphenated-key": true}

Trying to access apple.hyphenated-key would not work, you have to use bracket notation as such apple["hyphenated-key"].

Upvotes: 3

Related Questions