0

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.

2
  • 1
    FYI typeof is an operator, not a function, so the parentheses are unnecessary. The object's key must be a string, so you'd need to access it via apple["2"], not using a number via apple.2. Commented May 21, 2021 at 19:11
  • 2
    Dot notation is restricted to valid JS identifiers, 2 is not a valid JS identifier. Commented May 21, 2021 at 19:16

1 Answer 1

3

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"].

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

1 Comment

and after some research, we can't do foo.bar.baz for an object which is defined like foo={bar.baz : value}. I think objects as associative arrays make more sense in most of the little complicated-shaped objects. If anyone wants to unnderstand better, follow the link

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.