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.

saran
  • 356
  • 1
  • 3
  • 14
  • 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`. – Heretic Monkey May 21 '21 at 19:11
  • 2
    Dot notation is restricted to valid JS identifiers, `2` is not a valid JS identifier. – Dave Newton May 21 '21 at 19:16

1 Answers1

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

Steve Bunting
  • 419
  • 5
  • 12
  • 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](https://stackoverflow.com/questions/8067590/associative-array-versus-object-in-javascript) – saran May 21 '21 at 20:27